14. Graphs: Depth-First Search (DFS)
Go as deep as possible along one path before backing up. DFS is the tool for connected components, cycle detection, path existence and exhaustive search.
How it works
DFS visits a node, then recursively visits each unvisited neighbor before returning. The call stack holds the current path from the start node, so DFS naturally answers questions about paths and reachability.
The trace records each time we enter a node (first visit) and leave it (all neighbors done). Enter and leave times are the basis of cycle detection in directed graphs and of DFS-based topological sorting.
Diagram
graph LR
A --- B
A --- C
B --- D
B --- E
C --- F
E --- F
Step-by-step trace
Input: Same graph (A: B, C; B: A, D, E; C: A, F; D: B; E: B, F; F: C, E). Recursive DFS from A, neighbors in list order.
| Step | Event | Call stack (path) | Visit order |
|---|---|---|---|
| 1 | enter A | A | [A] |
| 2 | enter B | A -> B | [A, B] |
| 3 | enter D | A -> B -> D | [A, B, D] |
| 4 | leave D | A -> B | [A, B, D] |
| 5 | enter E | A -> B -> E | [A, B, D, E] |
| 6 | enter F | A -> B -> E -> F | [A, B, D, E, F] |
| 7 | enter C | A -> B -> E -> F -> C | [A, B, D, E, F, C] |
| 8 | leave C | A -> B -> E -> F | [A, B, D, E, F, C] |
| 9 | leave F | A -> B -> E | [A, B, D, E, F, C] |
| 10 | leave E | A -> B | [A, B, D, E, F, C] |
| 11 | leave B | A | [A, B, D, E, F, C] |
| 12 | leave A | (empty) | [A, B, D, E, F, C] |
Result: Visit order: [A, B, D, E, F, C].
Complexity
| Operation | Time | Space |
|---|---|---|
| DFS over V nodes and E edges | O(V + E) | O(V) for visited set and stack |
Python reference implementation
def dfs(graph, start):
order = []
seen = set()
def visit(node):
seen.add(node)
order.append(node)
for nb in graph[node]:
if nb not in seen:
visit(nb)
visit(start)
return order
Common mistakes and tips
- Deep graphs can exceed Python’s recursion limit (about 1000); switch to an explicit stack.
- Counting islands or components: start a DFS from every unvisited node and count the starts.
- Directed cycle detection needs three states (unvisited, on current path, done), not just a visited set.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Graphs: Breadth-First Search (BFS) | Next: Dijkstra’s Shortest Path |