Graph traversals
Write , and . Traversal order depends on the start vertex and the order of neighbours. An outer loop over unvisited vertices is needed to visit a disconnected graph fully; one source search visits only its reachable vertices.
7.1 Breadth-first search
Past papers · CS 2014–2026 (23 papers): 11 questions, 17 marks
BFS discovers vertices using a FIFO queue. Mark a vertex when enqueuing it, not when removing it; this prevents duplicate enqueues. Its tree gives shortest paths from the source in an unweighted graph, counting edges.
from collections import deque
def bfs(adj, source):
dist = {source: 0}
parent = {source: None}
queue = deque([source])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in dist:
dist[v] = dist[u] + 1
parent[v] = u
queue.append(v)
return dist, parent
Vertices are removed in nondecreasing level order. Neighbours discovered by the same parent form a queue block; arbitrary within-level permutations need not be possible. If the source is adjacent to all other vertices, any permutation of those vertices can be its neighbour order, giving possible discovery orders. In a binary tree, the number of vertices through level is at most ; equality permits a vertex at level to appear last at that index in a one-based BFS order. A BFS tree is not generally a shortest-path tree for every pair: a tree route between two nonsource vertices can miss a shorter graph route. Equal-level edges are allowed in undirected graphs; a same-level edge prevents a two-colouring by BFS level parity.
For a connected unweighted graph of diameter (largest pair distance), a BFS tree rooted anywhere has height satisfying : any pair is at distance at most the sum of its two distances to the root. On a tree, BFS to a farthest vertex followed by BFS from that vertex finds the diameter. This two-sweep rule is not guaranteed to find the exact diameter of a general graph.
7.2 Depth-first search and edge types
Past papers · CS 2014–2026 (23 papers): 5 questions, 9 marks · DA 2024–2026 (3 papers): 2 questions, 3 marks
DFS completely explores a newly discovered vertex before resuming its parent. White means undiscovered, gray means active, and black means finished. Recursive DFS uses a stack; iterative DFS must preserve neighbour progress if it is to reproduce recursive discovery and finishing order.
| Directed edge from to | Recognition during exploration | Interval relationship |
|---|---|---|
| Tree | was white; DFS discovers it | interval strictly inside |
| Back | is gray, an ancestor (or itself for a self-loop) | interval inside for proper ancestor |
| Forward | Black proper descendant, edge not used for discovery | interval strictly inside |
| Cross | Black vertex in another finished branch/tree | finishes before is discovered |
An undirected non-tree edge joins an ancestor and a descendant; there are no cross edges between incomparable vertices. The reverse view of the parent tree edge must not be mistaken for a cycle. A directed graph is acyclic exactly when DFS has no back edge. DFS generally does not give shortest distances.
If one rooted tree is both a BFS and DFS tree of a simple directed graph, a non-tree forward edge is impossible: it would jump to a descendant at least two levels down and contradict BFS distances. Back and cross edges may still exist.
DFS event intervals are nested for descendants and disjoint for separate completed branches.
7.3 Topological ordering
Past papers · CS 2014–2026 (23 papers): 1 question, 1 mark · DA 2024–2026 (3 papers): 1 question, 2 marks
A topological order places before for every directed edge . It exists exactly for a directed acyclic graph (DAG). Disconnected DAGs are allowed.
Kahn's algorithm repeatedly removes a current indegree-zero vertex and decreases the indegrees of its outgoing neighbours. If fewer than vertices are removed, a directed cycle remains. Alternatively, reverse DFS finishing order gives a topological order after confirming there is no back edge. Both methods take with adjacency lists.
To validate a proposed order, assign each vertex its position and check every edge goes forward. To count orders on a small graph, branch over each currently available zero-indegree vertex, update indegrees and sum the completions. Do not merely multiply the sizes of initial layers: new choices can appear before a layer empties. A topological order is unique exactly when Kahn's process has one choice at every step; equivalently, consecutive vertices of the order are joined by directed edges.
7.4 Reachability and strongly connected components
Past papers · CS 2014–2026 (23 papers): 1 question, 1 mark · DA 2024–2026 (3 papers): 1 question, 2 marks
BFS and DFS from the same source reach the same vertex set, though their orders differ. Reversing every edge exchanges source-to-target reachability with target-to-source reachability. It preserves every strongly connected component (SCC), including singleton components.
An SCC is a maximal set whose vertices reach one another. Contracting SCCs produces a DAG. Kosaraju's two-pass method first records DFS finishing order in , then runs DFS on the transpose in decreasing original finish time; each second-pass tree is one SCC. Interchanging the roles of and is also valid. Time and list storage are .
7.5 DFS low values, bridges and articulation points
Past papers · CS 2014–2026 (23 papers): 1 question, 2 marks
For a simple undirected graph, let be discovery time. The low value of is the earliest discovery reachable from its subtree by descending tree edges and then at most one back edge. Ignore the parent edge in the update.
The strict bridge inequality allows a back edge to the parent to save an edge from being a bridge only when it is a separate parallel edge; multigraph implementations must ignore the parent edge id, not all edges to the parent vertex. A DFS leaf cannot be an articulation point. An articulation point need not separate every one of its descendants from every ancestor: one child subtree can be separated while another has a back connection.
Last-minute recall
- BFS uses a queue; DFS uses a stack or recursion.
- Mark on discovery to avoid repeated work.
- Representation determines whether traversal costs linear or quadratic time.
- Undirected BFS edge endpoints differ by at most one level.
- DFS intervals never partially overlap.
- Reverse DFS finish order works for topological sorting only on a DAG.
- Reversing edges preserves SCCs, not a source's reachable set.
- CS: root articulation and nonroot articulation use different tests.