Skip to main content

Algorithms

Graph Algorithms

Graph algorithms are the highest-yield part of Algorithms: know BFS/DFS properties, when each shortest-path algorithm applies, every complexity, and how to run Dijkstra and Kruskal by hand.

~5 hrs ~2–3 marks · Must-score 10 samples · 10 practice · 10 cards

GATE CSE graph algorithms — BFS, DFS, edge classification, topological sort, strongly connected components, Dijkstra, Bellman-Ford, Floyd-Warshall, Kruskal and Prim with complexities and sample questions.

Learning outcomes

  • Compare adjacency list and matrix and state BFS/DFS complexity for each
  • Classify DFS edges, detect cycles, and produce topological orders and strongly connected components
  • Choose between Dijkstra, Bellman-Ford and Floyd-Warshall and quote their complexities and limitations
  • Run Kruskal and Prim on small graphs and state MST properties and complexities

Representations, BFS and DFS

  • Adjacency list: Θ(V + E) space, neighbours enumerated in O(degree). Adjacency matrix: Θ(V²) space, edge test in O(1), neighbours enumerated in Θ(V). Lists suit sparse graphs; matrices suit dense graphs.
  • BFS explores level by level using a QUEUE. It gives shortest paths (fewest edges) from the source in an UNWEIGHTED graph. Time Θ(V + E) with adjacency lists, Θ(V²) with a matrix. Space Θ(V).
  • DFS goes as deep as possible using a STACK (or recursion), recording discovery and finish times. Time Θ(V + E) with lists, Θ(V²) with a matrix. It does NOT give shortest paths.
  • BFS can test bipartiteness (2-colouring by levels), connectedness, and count components. A graph is bipartite iff it has no odd cycle.
  • In a BFS of an undirected graph every non-tree edge connects vertices whose levels differ by at most 1 (same level or adjacent levels).
  • Number of connected components of an undirected graph = number of BFS/DFS restarts. For a forest, components = V − E.
  • BFS enqueues each vertex once and scans each adjacency list once, so Θ(V + E); the queue holds at most about two consecutive levels, Θ(V) space in the worst case. Recursive DFS uses O(V) stack space in the worst case (a path graph).
  • Visit ORDER depends on the neighbour ordering; GATE states "alphabetical" or gives the lists. In the figure BFS from A visits A B C D E F, while DFS from A visits A B D C E F with back edges C–A and F–D.
  • Shape contrast: in the complete graph K_n, BFS from any vertex has only 2 levels, but DFS builds a single path of depth n − 1. BFS trees are shallow; DFS trees are deep.
  • Reachability and strong connectivity: BFS/DFS from s finds exactly the vertices reachable from s. G is strongly connected iff a search from one vertex reaches all vertices in G AND in the transpose graph.
OperationAdjacency listAdjacency matrix
SpaceΘ(V + E)Θ(V²)
Edge (u, v) exists?O(deg u)O(1)
List neighbours of uO(deg u)Θ(V)
BFS / DFSΘ(V + E)Θ(V²)

Worked example

Problem. Time to run BFS from one vertex on a graph with V vertices and E edges stored as an adjacency matrix?

Solution. Each vertex dequeued scans a full row of V entries: V × V = Θ(V²).

The same six-vertex graph shown twice: BFS layers L0 to L3 on the left and the DFS tree with back edges on the right
BFS from A gives layers {A}, {B,C}, {D,E}, {F}; DFS from A gives a deep tree with two back edges.

DFS applications: edge types, cycles, topological sort, SCC

  • DFS edge classification in a directed graph: tree edges, back edges (to an ancestor), forward edges (to a descendant, not tree), cross edges (between unrelated subtrees). In an UNDIRECTED graph only tree edges and back edges occur.
  • A directed graph has a cycle if and only if DFS finds a BACK edge. An undirected graph has a cycle iff DFS finds a non-parent visited neighbour.
  • Topological sort exists only for a DAG: order vertices so that every edge u → v has u before v. Obtain it by listing vertices in DECREASING DFS finish time, or by Kahn algorithm (repeatedly remove vertices of in-degree 0). Time Θ(V + E). A DAG can have several topological orders; the order is unique iff a Hamiltonian path exists.
  • Strongly connected components (SCC): maximal sets of mutually reachable vertices. Kosaraju: DFS on G to get finish times, DFS on the transpose graph in decreasing finish order. Tarjan does it in one DFS. Both are Θ(V + E). Contracting each SCC gives a DAG.
  • Articulation point: removal disconnects the graph. In a DFS tree the root is one iff it has at least 2 children; a non-root u is one iff some child subtree has no back edge to a proper ancestor of u.
  • Parenthesis theorem: discovery and finish intervals of two vertices are either disjoint or nested, never partially overlapping.

Formulas to remember

  • Topological order = decreasing DFS finish time
  • DAG ⟺ no back edge in DFS
  • SCC (Kosaraju/Tarjan): Θ(V + E)

Worked example

Problem. Count the topological orderings of the DAG with edges A→B, A→C, B→D, C→D.

Solution. A must be first and D last; B and C can be in either order: A B C D and A C B D, so 2 orderings.

Single-source and all-pairs shortest paths

  • Relaxation: if d[u] + w(u, v) < d[v] then d[v] = d[u] + w(u, v). All shortest-path algorithms are built from relaxations.
  • Dijkstra: greedily extracts the unsettled vertex with the smallest distance. Works ONLY for non-negative weights (it may fail with negative edges, even without negative cycles). Time Θ(V²) with an array, O((V + E) log V) with a binary heap, O(E + V log V) with a Fibonacci heap.
  • Bellman-Ford: relax every edge V − 1 times. Handles negative edge weights, detects a reachable negative cycle in one extra pass. Time Θ(VE).
  • DAG shortest paths: process vertices in topological order and relax outgoing edges. Θ(V + E), valid even with negative weights.
  • Floyd-Warshall: DP over intermediate vertices, d_k[i][j] = min(d_{k−1}[i][j], d_{k−1}[i][k] + d_{k−1}[k][j]). Time Θ(V³), space Θ(V²), handles negative edges but not negative cycles (detected by a negative diagonal entry).
  • Johnson algorithm reweights edges using Bellman-Ford and then runs Dijkstra from each vertex: O(VE + V² log V) for sparse graphs.
  • For unweighted graphs BFS gives shortest paths in Θ(V + E).
  • Dijkstra invariant: when a vertex is extracted its distance is final (non-negative weights), every edge is relaxed exactly once, so there are at most E decrease-key operations: O((V + E) log V) with a binary heap.
  • Why negative edges break Dijkstra: with S→A = 3, S→B = 4, B→A = −2, Dijkstra settles A at 3 first, but the true shortest distance to A is 4 − 2 = 2. Once a vertex is settled it is never revisited.
  • Bellman-Ford can stop early when a whole pass changes nothing; a relaxation still possible in pass V proves a reachable negative cycle. Time Θ(VE), so slower than Dijkstra but more general.
  • Floyd-Warshall loop order is k (intermediate vertex) OUTERMOST, then i, then j. Putting k inside gives a wrong algorithm; the recurrence is a DP over the set of allowed intermediate vertices.
  • Density rule: array Dijkstra Θ(V²) beats heap Dijkstra O((V + E) log V) when E is close to V²; for sparse graphs (E ≈ V) the heap version Θ(V log V) is far better.
AlgorithmProblemNegative edges?Time
BFSSingle-source, unweightedN/AΘ(V + E)
Dijkstra (array)Single-sourceNoΘ(V²)
Dijkstra (binary heap)Single-sourceNoO((V + E) log V)
Bellman-FordSingle-sourceYes (detects negative cycle)Θ(VE)
DAG relaxationSingle-source on a DAGYesΘ(V + E)
Floyd-WarshallAll-pairsYes (no negative cycle)Θ(V³)

Worked example

Problem. Undirected edges: S–A 4, S–B 1, B–A 2, A–C 1, B–C 5. Shortest distance from S to C?

Solution. Dijkstra: d(B) = 1, d(A) = min(4, 1 + 2) = 3, d(C) = min(3 + 1, 1 + 5) = 4. Path S → B → A → C = 4.

Weighted directed graph with the shortest path tree highlighted and a table of distances after each vertex is settled
Dijkstra from S: vertices settle in order S, B, A, C, D with final distances 0, 3, 1, 4, 7.

Minimum spanning trees: Kruskal and Prim

  • A spanning tree of a connected graph with V vertices has exactly V − 1 edges. An MST minimises total weight.
  • Kruskal: sort edges ascending, scan and add an edge if it joins two different components (Union-Find). Θ(E log E) = Θ(E log V). Works on disconnected graphs (gives a spanning forest).
  • Prim: start from a vertex and repeatedly add the cheapest edge connecting the tree to a new vertex. Θ(V²) with matrix and array; Θ(E log V) with binary heap and adjacency list; Θ(E + V log V) with a Fibonacci heap.
  • Cut property justifies both: the lightest edge across any cut is in some MST. If edge weights are distinct the MST is unique; all MSTs of a graph have equal total weight and the same sorted list of edge weights.
  • Maximum spanning tree: negate weights or sort descending. The path in an MST between two vertices minimises the maximum edge weight (minimax/bottleneck path).
  • Choice rule: for sparse graphs (E ≈ V) Kruskal or heap-Prim; for dense graphs (E ≈ V²) matrix-Prim at Θ(V²) beats Θ(E log V).
  • In the figure Kruskal accepts BC, AC, DE, EF and BD (it skips AB because A and B are already connected), while Prim from A adds AC, CB, BD, DE, EF. The sets of edges coincide and the total weight is 13 either way.
  • Several MSTs appear only when equal-weight edges compete (for example a triangle with three equal edges has 3 MSTs). All distinct weights ⇒ exactly one MST; a graph that is itself a tree has itself as the only spanning tree.
  • Adding the same constant to every edge weight does NOT change which trees are MSTs (every spanning tree has V − 1 edges), but it CAN change shortest paths, so an MST is not a shortest-path tree.
  • Kruskal can stop after V − 1 accepted edges; on a disconnected graph it returns a minimum spanning FOREST. Borůvka (merge the cheapest edge of every component) takes at most log V phases.
MST algorithmStrategyData structureTime
KruskalPick lightest safe edge globallySort + Union-FindΘ(E log E)
Prim (matrix)Grow one treeArrayΘ(V²)
Prim (heap)Grow one treeBinary heap + listΘ(E log V)

Worked example

Problem. Edges: AB 4, AC 2, BC 1, BD 5, CD 8, CE 10, DE 2, DF 6, EF 3 on vertices A–F. Find the MST weight.

Solution. Sorted: BC 1, AC 2, DE 2, EF 3, AB 4 (cycle, skip), BD 5 (accept). Weight = 1 + 2 + 2 + 3 + 5 = 13 with 5 = V − 1 edges.

Weighted undirected graph on six vertices with minimum spanning tree edges highlighted and side panels listing Kruskal and Prim steps
The same graph solved by Kruskal and by Prim: both give an MST of weight 13.

Counting facts and graph properties

  • Simple undirected graph: at most V(V−1)/2 edges. Simple directed graph: at most V(V−1) edges. A DAG has at most V(V−1)/2 edges (a total order).
  • Handshaking lemma: Σ deg(v) = 2E, so the number of odd-degree vertices is even. A connected graph needs at least V − 1 edges; a tree has exactly V − 1.
  • A forest with V vertices and E edges has V − E components. Adding an edge between two vertices of the same component creates exactly one new cycle.
  • Euler circuit exists iff the graph is connected and every vertex has even degree (directed: in-degree = out-degree). Deciding it is in P, unlike Hamiltonian cycle (NP-complete).
  • A graph is bipartite iff it has no odd-length cycle, iff BFS 2-colouring succeeds. Trees and even cycles are bipartite; C5 is not.
  • Path in an unweighted tree between two vertices is unique; BFS tree depth gives the eccentricity of the source.
Graph typeMaximum edgesMinimum edges for connectivity
Simple undirectedV(V−1)/2V − 1
Simple directedV(V−1)V − 1 (weak connectivity)
DAGV(V−1)/20
TreeV − 1V − 1

Worked example

Problem. A forest has 10 vertices and 7 edges. How many connected components?

Solution. Components = V − E = 10 − 7 = 3.

Worked trace — Bellman-Ford with a negative edge

  • Graph: S→A 4, S→B 5, B→A −3, A→C 2, B→C 6. Edge order in every pass: (S,A), (S,B), (B,A), (A,C), (B,C). Start d = (S 0, A ∞, B ∞, C ∞).
  • Pass 1: (S,A) sets A = 4; (S,B) sets B = 5; (B,A) gives 5 − 3 = 2 < 4 so A = 2; (A,C) sets C = 4; (B,C) gives 11, no change. After pass 1: A = 2, B = 5, C = 4.
  • Pass 2: no edge relaxes, so the algorithm has converged (it could stop here). V − 1 = 3 passes is only the worst-case bound; a V-th pass that still relaxes would signal a negative cycle.
  • Dijkstra on the same graph settles S, then A (distance 4), then B (5), then C (6). When B later offers A a better distance 2, A is already settled and its neighbours are never re-examined, so C stays at 6 instead of the true 4.
  • Edge order changes how many passes are needed (the order (B,A) first would need an extra pass), but never the final answer.

Worked example

Problem. In the graph above, what is the shortest distance from S to C?

Solution. S → B → A → C = 5 − 3 + 2 = 4. The route S → A → C costs 6 and S → B → C costs 11.

GATE exam tricks — choosing the right algorithm

  • Negative edge weights → Dijkstra is unsafe. Use Bellman-Ford (single source) or Floyd-Warshall (all pairs). Negative cycle reachable → shortest path undefined.
  • Unweighted shortest path → BFS. Weighted non-negative → Dijkstra. DAG → topological relaxation in Θ(V + E).
  • Complexities with a matrix representation replace V + E by V². Always check which representation the stem gives.
  • Dijkstra with a heap: O((V + E) log V); with array: Θ(V²) — pick the better one by density (E vs V²/log V).
  • DFS finish times: topological order is decreasing finish time; in a DAG, for every edge u → v, finish(u) > finish(v).
  • Counting topological orders: draw the DAG, fix forced positions, and permute the unconstrained vertices.
  • Bellman-Ford runs V − 1 passes; if a V-th pass still relaxes an edge a negative cycle exists.
  • MST numerical questions: sort edges, accept an edge unless it forms a cycle, stop after V − 1 acceptances; weights equal across Kruskal and Prim.
  • Worked example 2 (Kahn): edges A→C, B→C, C→D, B→E, E→D give in-degrees A 0, B 0, C 2, D 2, E 1. Remove A (C becomes 1), remove B (C becomes 0, E becomes 0), remove C (D becomes 1), remove E (D becomes 0), remove D. Order: A B C E D.
  • Worked example 3 (what changes with a matrix): BFS on a graph stored as an adjacency matrix is Θ(V²) even if E = 5; Prim with a matrix and array is Θ(V²) independent of E.
  • If an option says "Dijkstra works if there is no negative CYCLE", reject it: Dijkstra needs no negative EDGES. Bellman-Ford is the algorithm that tolerates negative edges without negative cycles.

Worked example

Problem. After DFS of a DAG, for the edge u → v which finish time is larger?

Solution. finish(u) > finish(v), because v finishes before u does; this is why decreasing finish time gives a topological order.

Exam tips

  • Check the representation (list or matrix) before quoting BFS/DFS/Prim complexity.
  • Dijkstra needs non-negative weights; Bellman-Ford and Floyd-Warshall allow negative edges but not negative cycles.
  • Topological sorting and DFS cycle detection depend only on DAG/back-edge facts.
  • For MST by hand, sort edges first and keep a running list of components.
  • Know the counting facts: V − 1 edges in a tree/MST, V(V−1)/2 maximum undirected edges, components of a forest = V − E.
Exam pattern · 10 questions

GATE sample questions & answers

10 GATE-style MCQs for Graph Algorithms with full explanations. Attempt each question before revealing the answer.

Q1 Traversal complexity

The time complexity of BFS or DFS on a graph with V vertices and E edges stored as adjacency lists is:

  • A) Θ(V)
  • B) Θ(V + E)
  • C) Θ(V · E)
  • D) Θ(V²)
Show answer & explanation

Answer: B

Every vertex is processed once and every adjacency list is scanned once, giving Θ(V + E).

Q2

Dijkstra algorithm implemented with a binary min-heap and adjacency lists runs in:

  • A) O(V²)
  • B) O((V + E) log V)
  • C) O(VE)
  • D) O(V³)
Show answer & explanation

Answer: B

Each vertex extraction and each successful relaxation (decrease-key) costs O(log V).

Q3

Which shortest-path algorithm correctly handles graphs with negative edge weights (no negative cycle) from a single source?

  • A) Dijkstra
  • B) Bellman-Ford
  • C) BFS
  • D) Prim
Show answer & explanation

Answer: B

Bellman-Ford relaxes all edges V − 1 times and tolerates negative edges. Dijkstra and BFS assume non-negative (or equal) weights.

Q4

The number of distinct topological orderings of the DAG with edges A→B, A→C, B→D, C→D is:

  • A) 1
  • B) 2
  • C) 3
  • D) 6
Show answer & explanation

Answer: B

A is first, D is last, and B, C can appear in either order: A B C D and A C B D.

Q5

A DFS of an undirected graph can produce which edge types?

  • A) Tree and back edges only
  • B) Tree, back and forward edges
  • C) Tree, back and cross edges
  • D) All four types
Show answer & explanation

Answer: A

In an undirected graph every non-tree edge connects a vertex to an ancestor or descendant, so it is a back edge; forward and cross edges do not occur.

Q6

The Floyd-Warshall algorithm for all-pairs shortest paths on V vertices has time complexity:

  • A) Θ(V²)
  • B) Θ(V² log V)
  • C) Θ(V³)
  • D) Θ(V E)
Show answer & explanation

Answer: C

Three nested loops over the intermediate vertex k and the pair (i, j).

Q7

How many edges does a minimum spanning tree of a connected graph with V vertices have?

  • A) V
  • B) V − 1
  • C) V + 1
  • D) E
Show answer & explanation

Answer: B

A spanning tree is a connected acyclic subgraph on all V vertices, which has V − 1 edges.

Q8

A directed graph is acyclic if and only if a depth-first search of it produces:

  • A) No tree edges
  • B) No back edges
  • C) No cross edges
  • D) No forward edges
Show answer & explanation

Answer: B

A back edge closes a cycle with tree edges; conversely every cycle contains a back edge in DFS.

Q9

Undirected edges: S–A 4, S–B 1, B–A 2, A–C 1, B–C 5. The shortest distance from S to C is:

  • A) 4
  • B) 5
  • C) 6
  • D) 7
Show answer & explanation

Answer: A

S → B → A → C = 1 + 2 + 1 = 4, shorter than S → A → C = 5 and S → B → C = 6.

Q10

The maximum number of edges in a simple undirected graph with 10 vertices is:

  • A) 20
  • B) 45
  • C) 90
  • D) 100
Show answer & explanation

Answer: B

V(V − 1)/2 = 10·9/2 = 45.

Topic drill · 10 questions

10 practice questions — Graph Algorithms

Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.

P1

BFS on a graph with V vertices stored as an adjacency matrix takes:

  • A) Θ(V)
  • B) Θ(V + E)
  • C) Θ(V²)
  • D) Θ(E²)
Show answer & explanation

Answer: C) Θ(V²)

Each dequeued vertex scans an entire matrix row of length V.

P2

An undirected acyclic graph with 10 vertices and 7 edges has how many connected components?

  • A) 1
  • B) 2
  • C) 3
  • D) 7
Show answer & explanation

Answer: C) 3

For a forest, components = V − E = 10 − 7 = 3.

P3

The maximum number of edges in a DAG with n vertices is:

  • A) n − 1
  • B) n(n − 1)/2
  • C) n(n − 1)
  • D) n²
Show answer & explanation

Answer: B) n(n − 1)/2

Fix a topological order and add every forward edge: C(n, 2) edges, with no cycle.

P4

Kosaraju algorithm for strongly connected components runs in:

  • A) Θ(V + E)
  • B) Θ(V²) only
  • C) Θ(VE)
  • D) Θ(V³)
Show answer & explanation

Answer: A) Θ(V + E)

It performs two DFS traversals and one graph transpose, each in Θ(V + E).

P5

Bellman-Ford single-source shortest path has time complexity:

  • A) O(V + E)
  • B) O(E log V)
  • C) O(VE)
  • D) O(V³)
Show answer & explanation

Answer: C) O(VE)

V − 1 passes, each relaxing all E edges.

P6

BFS gives the correct shortest-path distances from a source when the edges are:

  • A) Of arbitrary positive weights
  • B) Unweighted (all equal weight)
  • C) Negative
  • D) Directed only
Show answer & explanation

Answer: B) Unweighted (all equal weight)

BFS minimises the number of edges, which equals distance only if all edges have the same weight.

P7

Prim algorithm on a dense graph with adjacency matrix is best implemented in time:

  • A) Θ(V)
  • B) Θ(V²)
  • C) Θ(V³)
  • D) Θ(E²)
Show answer & explanation

Answer: B) Θ(V²)

V iterations with O(V) minimum selection and O(V) key updates each.

P8

Edges: AB 4, AC 2, BC 1, BD 5, CD 8, CE 10, DE 2, DF 6, EF 3. The weight of the MST is:

  • A) 11
  • B) 12
  • C) 13
  • D) 14
Show answer & explanation

Answer: C) 13

Kruskal accepts BC 1, AC 2, DE 2, EF 3 and BD 5 (AB would close a cycle): total 13 with 5 edges.

P9

In a DFS tree of a connected undirected graph, the root is an articulation point if and only if:

  • A) It has exactly one child
  • B) It has at least two children
  • C) It has a back edge
  • D) It is a leaf
Show answer & explanation

Answer: B) It has at least two children

With two or more children, the subtrees are not connected except through the root, so removing it disconnects the graph.

P10

Which of the following graphs is NOT bipartite?

  • A) A tree
  • B) A cycle on 6 vertices
  • C) A cycle on 5 vertices
  • D) A path on 7 vertices
Show answer & explanation

Answer: C) A cycle on 5 vertices

A graph is bipartite iff it has no odd cycle; C5 is an odd cycle.

Topic FAQs

Why does Dijkstra fail with negative edges?

It permanently fixes a vertex distance when extracted, assuming no later path can be shorter; a negative edge can later give a shorter path to a settled vertex.

Can DFS produce shortest paths?

No. DFS explores deeply and does not guarantee fewest edges; BFS does for unweighted graphs.

When is Prim faster than Kruskal?

On dense graphs, where Θ(V²) matrix-Prim beats Θ(E log E) Kruskal; on sparse graphs both are near Θ(E log V).

What is the difference between a back edge and a cross edge?

A back edge points to an ancestor in the DFS tree (forming a cycle), whereas a cross edge connects vertices in different subtrees with no ancestor relationship.

Quick revision · 10 cards

10 flashcards — Graph Algorithms

Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.

Q1 What data structures do BFS and DFS use and what do they compute?
Q2 What is the time complexity of BFS and DFS for adjacency lists versus an adjacency matrix?
Q3 How can you detect a cycle in a directed graph using DFS?
Q4 How do you obtain a topological ordering using DFS?
Q5 Why can Dijkstra algorithm fail on graphs with negative edge weights?
Q6 What is the time complexity of Bellman-Ford and how does it detect negative cycles?
Q7 What is the recurrence of Floyd-Warshall?
Q8 How do Kruskal and Prim algorithms differ?
Q9 What are the time complexities of Prim algorithm with different data structures?
Q10 What are strongly connected components and how fast can they be found?