Algorithms · Graph Traversal, DFS Applications, Topological Sort and SCC
Graph Representations and Breadth-First Search
A graph is a set of vertices and edges . Almost every graph algorithm (shortest paths, cycle detection, topological sort, connectivity, bipartiteness, SCC) begins by visiting every vertex in a disciplined order. The two disciplined orders are:
- BFS (Breadth-First Search) — explore in "rings" of increasing distance from a source. Uses a queue.
- DFS (Depth-First Search) — go as deep as possible, then backtrack. Uses a stack (or recursion).
Throughout, let and . (GATE questions use both and ; they mean the same thing.)
2.1 Adjacency matrix
An array with if edge , else . Undirected graphs give a symmetric matrix; weighted graphs store the weight (and for no edge).
2.2 Adjacency list
An array of lists; list contains every neighbour of . Undirected edge appears twice (once in 's list, once in 's); directed edge appears once.
2.3 Cost table (memorise this)
| Operation | Adjacency matrix | Adjacency list |
|---|---|---|
| Space | (directed), (undirected) | |
| Test if | ||
| List all neighbours of | ||
| Add edge | ||
| Remove edge | ||
| Add vertex | (reallocate) | |
| Total time to scan all edges | ||
| BFS / DFS time |
Key consequence: BFS and DFS are on lists but on a matrix, because with a matrix you must scan an entire row of length to find the (possibly few) neighbours of a vertex.
Which representation does GATE assume? If the question says "adjacency list" or "adjacency matrix", use that. If it says nothing and asks for the complexity of BFS/DFS, the standard answer is (list). If it says "dense graph" or "matrix", answer .
3.1 The algorithm
BFS(G, s):
for each v in V: colour[v] = WHITE; d[v] = INF; pi[v] = NIL
colour[s] = GRAY; d[s] = 0; pi[s] = NIL
Q = empty queue; ENQUEUE(Q, s)
while Q not empty:
u = DEQUEUE(Q)
for each v in Adj[u]:
if colour[v] == WHITE:
colour[v] = GRAY
d[v] = d[u] + 1
pi[v] = u
ENQUEUE(Q, v)
colour[u] = BLACK
colour: WHITE = undiscovered, GRAY = discovered but not finished, BLACK = finished.d[v]: number of edges on the shortest path from to (in an unweighted graph).pi[v]: BFS-tree parent.
3.2 Worked trace on 7 vertices
Graph (undirected), vertices :
1 -- 2 -- 3
| | |
4 -- 5 6
|
7
Edges: .
Adjacency lists (sorted ascending, as GATE usually assumes):
| Vertex | Neighbours |
|---|---|
| 1 | 2, 4 |
| 2 | 1, 3, 5 |
| 3 | 2, 6 |
| 4 | 1, 5 |
| 5 | 2, 4, 7 |
| 6 | 3 |
| 7 | 5 |
Source . Trace (queue shown front-to-back):
| Step | Dequeue | Queue after processing | values set this step |
|---|---|---|---|
| 0 | — | [1] | |
| 1 | 1 | [2, 4] | |
| 2 | 2 | [4, 3, 5] | |
| 3 | 4 | [3, 5] | (5 already GRAY, skip) |
| 4 | 3 | [5, 6] | |
| 5 | 5 | [6, 7] | |
| 6 | 6 | [7] | — |
| 7 | 7 | [] | — |
Final distances: .
Check: via (3 edges) — correct, no shorter path exists. via — correct.
BFS tree (parent pointers):
1
/ \
2 4
/ \
3 5
| \
6 7
3.3 Properties
- Shortest paths in unweighted graphs. equals the minimum number of edges from to . Proof idea: BFS discovers vertices in non-decreasing order of ; when is first discovered from , is minimal.
- Levels. All vertices with the same form a level; BFS visits level entirely before level . The queue never contains vertices from more than two consecutive levels.
- BFS tree. The edges form a tree rooted at spanning exactly the vertices reachable from . Every non-tree edge of an undirected graph joins two vertices whose levels differ by at most 1 (it is a "cross" edge between same or adjacent levels — see §5.4).
- Complexity. Each vertex is enqueued at most once ( total queue work); each adjacency list is scanned once ( total). With lists: . With a matrix: .
- BFS does not work for weighted graphs — use Dijkstra instead.
3.4 BFS order is not unique
The order in which neighbours are enqueued depends on the order of the adjacency lists. GATE questions exploit this: "which of the following is a valid BFS order?" — you must check that the order is consistent with some adjacency-list ordering, not a specific one.
Rule for checking a BFS order: simulate the queue. Start with ; repeatedly take the next unprocessed vertex of the given sequence (it must already be in the queue) and look at its still-undiscovered neighbours: they must be the next entries of the sequence, in any order among themselves. Equivalently, every vertex other than must have an earlier neighbour (its parent = its earliest-listed neighbour), the distances must be non-decreasing along the sequence, and the parents' positions must be non-decreasing: children of an earlier vertex come before children of a later vertex. Example: adjacent to ; adjacent to ; adjacent to . The order is not a BFS order (the child of precedes the child of ), although it satisfies "each vertex has a neighbour in the previous level".