Sub topic 16
BFS and DFS: traversal order, edge types, and complexity
This chapter assumes you know graph terminology (vertices, edges, directed, connected), how queues and stacks work, and Big-O notation. It also assumes you can read short Python. Graphs are stored as adjacency lists, as in the previous chapter, so graph[u] is the list of neighbours of u.
Breadth-first search
Breadth-first search (BFS) explores a graph in layers. It visits the source, then every vertex one edge away, then every vertex two edges away, and so on. A FIFO queue produces this order.
from collections import deque
def bfs(graph, source):
dist = {source: 0}
parent = {source: None}
queue = deque([source])
while queue:
u = queue.popleft()
for v in graph[u]:
if v not in dist: # mark when discovered, not when dequeued
dist[v] = dist[u] + 1
parent[v] = u
queue.append(v)
return dist, parent
g = {'A': ['B', 'D'], 'B': ['C'], 'C': ['A', 'D'], 'D': [], 'E': ['D']}
print(bfs(g, 'A'))For an unweighted graph, dist[v] is the minimum number of edges from the source to v. Following parent links gives one shortest path. Vertices that BFS cannot reach never appear in dist.
Depth-first search
Depth-first search (DFS) follows one path as far as it can, then backtracks. It uses a stack, either explicitly or through recursion. We give each vertex a discovery time and a finish time, and we colour vertices:
- White: not yet discovered.
- Gray: discovered, still on the recursion stack.
- Black: finished, with all neighbours explored.
def dfs_classify(graph):
color = {u: 'white' for u in graph}
disc, fin, kinds = {}, {}, {}
clock = 0
def visit(u):
nonlocal clock
clock += 1
disc[u] = clock
color[u] = 'gray'
for v in graph[u]:
if color[v] == 'white':
kinds[(u, v)] = 'tree'
visit(v)
elif color[v] == 'gray':
kinds[(u, v)] = 'back'
else:
kinds[(u, v)] = 'forward' if disc[u] < disc[v] else 'cross'
color[u] = 'black'
clock += 1
fin[u] = clock
for u in graph:
if color[u] == 'white':
visit(u)
return disc, fin, kinds
g = {'A': ['B', 'D'], 'B': ['C'], 'C': ['A', 'D'], 'D': [], 'E': ['D']}
disc, fin, kinds = dfs_classify(g)
print(disc) # {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 9}
print(fin) # {'D': 5, 'C': 6, 'B': 7, 'A': 8, 'E': 10}
for edge, kind in kinds.items():
print(edge, kind)The outer loop over all vertices is what makes this a depth-first forest. Without it, DFS would miss vertices that the first start vertex cannot reach (here, E).
Edge types in a directed graph
DFS sorts every edge (u, v) into one of four classes, based on the colour of v when the edge is examined.
| Edge type | Colour of `v` | Meaning |
|---|---|---|
| Tree | white | `v` is discovered through this edge |
| Back | gray | `v` is an ancestor of `u` (or `u` itself, for a self-loop) |
| Forward | black, `disc[u] < disc[v]` | `v` is a non-child descendant of `u` |
| Cross | black, `disc[u] > disc[v]` | `v` is in another subtree or another tree |
A directed graph has a cycle if and only if DFS finds a back edge. This fact drives cycle detection and topological sort, which is the next chapter's topic.
In an undirected graph, DFS produces only tree and back edges. Forward and cross edges cannot occur. Each undirected edge appears twice in the adjacency lists, so ignore the edge back to the parent when you look for cycles.
BFS has its own rule. In an undirected graph, every non-tree edge joins vertices whose levels differ by at most one. In a directed graph, an edge (u, v) always satisfies dist[v] <= dist[u] + 1.
Complexity
| Operation | Adjacency list | Adjacency matrix |
|---|---|---|
| BFS or DFS time | O(V + E) | O(V²) |
| Space for the graph | O(V + E) | O(V²) |
| Extra space (queue, stack, colours) | O(V) | O(V) |
The O(V + E) bound comes from two counts. Each vertex is enqueued or visited once, which costs O(V). Each adjacency list is scanned once, and the lists have total length E for a directed graph or 2E for an undirected one. With a matrix, finding the neighbours of one vertex scans a whole row, so the total is V × V.
Common errors
- Using BFS distances on a weighted graph. BFS counts edges, not weights. Use Dijkstra or Bellman-Ford instead.
- Forgetting the outer loop in DFS, so disconnected vertices never get times or classes.
- Hitting Python's default recursion limit (about 1000 frames) on a long path. Raise it with
sys.setrecursionlimitor write DFS with an explicit stack. - Reading a gray neighbour as a cycle in an undirected graph. It is only a cycle if that neighbour is not the parent through which you arrived.
- Mixing up "stack-based" traversal orders. A DFS with an explicit stack can visit neighbours in the reverse of the recursive order unless you push them in reverse.
Exercise
Run dfs_classify on the graph {'P': ['Q', 'R'], 'Q': ['R'], 'R': ['P'], 'S': ['Q']} with vertices taken in the order P, Q, R, S. List each edge's class.
Show answer
Start at P (disc 1). The edge P→Q is a tree edge and Q gets disc 2. The edge Q→R is a tree edge and R gets disc 3. The edge R→P goes to a gray vertex, so it is a back edge. R finishes, then Q finishes. Back at P, the edge P→R points to a black vertex with disc[P] = 1 < disc[R] = 3, so it is a forward edge. P finishes. S starts a new tree, and S→Q points to a black vertex with disc[S] > disc[Q], so it is a cross edge. The graph has a cycle because there is a back edge.
Exercise
A connected graph has V = 1000 vertices and E = 1200 edges. Compare the running time of BFS using an adjacency list and using an adjacency matrix, in basic steps.
Show answer
With an adjacency list, BFS takes about V + E = 2200 steps (up to V + 2E = 3400 if the graph is undirected). With an adjacency matrix it takes about V² = 1,000,000 steps, because each of the 1000 dequeued vertices scans a row of 1000 entries. The graph is sparse, so the list is far cheaper.