Graphs and paths · 26 / 53
BFS, DFS and traversal invariants
Understand → trace → implement → justify
1 min reading · allow extra time for practiceBFS explores layers using a queue. On unweighted or equal-weight edges, first discovery gives minimum edge count. Mark vertices when enqueuing to avoid repeated queue entries. Parent links reconstruct the path.
DFS follows a branch using a stack or recursion. Discovery/finish times and active-stack colours expose back edges and ordering. In an undirected cycle test, exclude the parent edge; parallel edges may require edge IDs. Recursive depth can reach V.
Restart from every unvisited vertex to cover disconnected graphs. Neighbour order changes traversal order but not correct BFS distances. BFS is not a general weighted shortest-path algorithm; separate edge count from cost.
A worked trace
A→B,C; B→D; C→D gives distances A0,B1,C1,D2. Marking on enqueue prevents addingD again fromC.
Cost and assumptions
Adjacency-list traversal O(V+E) time, O(V) auxiliary space; matrices require O(V²) scanning.
Executable example
Run with Python 3. Assertions check a small example; they do not constitute a general correctness proof. Some advanced examples are explicitly small models or reference oracles, not full production implementations.
from collections import deque
def bfs(g, start):
distance, parent = {start: 0}, {start: None}
q = deque([start])
while q:
u = q.popleft()
for v in g[u]:
if v not in distance:
distance[v], parent[v] = distance[u]+1, u
q.append(v)
return distance, parent
assert bfs({"A":["B","C"],"B":["D"],"C":["D"],"D":[]},"A")[0]["D"] == 2TEST YOUR UNDERSTANDING
Your turn
If one edge costs100 and two edges cost1+1, which path does BFS select?
Reveal the reasoning
It may choose the one-edge path, minimising edge count rather than cost. Use Dijkstra for nonnegative weighted graphs.
Take it further
- Write down the input contract and the invariant before changing the example.
- Add empty, boundary, duplicate and adversarial cases where they are relevant. Compare with a simple oracle.
- Derive the cost under the stated model; measure several input sizes and explain discrepancies.
Primary reading & lecture notes
Original explanations in this course; these references provide proofs and further reading. Source links may cover the broader module.
MIT 6.006 · Introduction to Algorithms ↗