Chapter 7

Graph traversals

Write G=(V,E)G=(V,E), nv=∣V∣n_v=|V| and ne=∣E∣n_e=|E|. 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.

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 nv−1n_v-1 vertices, any permutation of those vertices can be its neighbour order, giving (nv−1)!(n_v-1)! possible discovery orders. In a binary tree, the number of vertices through level hh is at most 1+2+⋯+2h=2h+1−11+2+\cdots+2^h=2^{h+1}-1; equality permits a vertex at level hh 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 DD (largest pair distance), a BFS tree rooted anywhere has height hh satisfying ⌈D/2⌉≤h≤D\lceil D/2\rceil\le h\le D: 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.

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 uu to vvRecognition during explorationInterval relationship
Treevv was white; DFS discovers itvv interval strictly inside uu
Backvv is gray, an ancestor (or itself for a self-loop)uu interval inside vv for proper ancestor
ForwardBlack proper descendant, edge not used for discoveryvv interval strictly inside uu
CrossBlack vertex in another finished branch/treevv finishes before uu 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.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 uu before vv for every directed edge u→vu\to v. 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 nvn_v 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 Θ(nv+ne)\Theta(n_v+n_e) 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 GG, then runs DFS on the transpose GRG^R in decreasing original finish time; each second-pass tree is one SCC. Interchanging the roles of GG and GRG^R is also valid. Time and list storage are O(nv+ne)O(n_v+n_e).

7.5 DFS low values, bridges and articulation pointsCS

Past papers · CS 2014–2026 (23 papers): 1 question, 2 marks

For a simple undirected graph, let df(u)d_f(u) be discovery time. The low value of uu 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.

Revise offline: the whole Algorithms handbook as one PDF

52 pages · 2.6 MBFree to read online. Sign in to download the PDF.We save the handbook, version and request time in My downloads. Privacy policy

All chapters · Corrections