Sub topic 4
Writing DFS Recursively
This chapter assumes you are comfortable with Python functions, sets, and dictionaries, and that you know how recursion uses the call stack. It builds on the adjacency-list representation and the visited set from earlier chapters.
Why Recursion Fits DFS
Depth-first search goes as deep as it can along one path, then backs up to try the next option. Recursion behaves the same way. When a function calls itself on a neighbor, the current call pauses until that neighbor's exploration is completely finished. Then the current call resumes and moves to its next neighbor. Python's call stack does the backtracking for you, so you never write any code to "go back."
Each call to the recursive function does three things for one vertex:
- Mark the vertex as visited.
- Record it, or do whatever work the problem needs.
- Call itself on each neighbor that has not been visited yet.
The Implementation
def dfs_recursive(graph, start):
visited = set()
order = []
def visit(node):
visited.add(node)
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visit(neighbor)
visit(start)
return order
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(dfs_recursive(graph, "A")) # ['A', 'B', 'D', 'C']The inner function visit is a closure. It reads and updates visited and order from the enclosing scope, so neither has to be passed down through every call. Because visit mutates these objects and never rebinds them, it does not need a nonlocal declaration.
Tracing the Calls
From A, the loop first reaches B, and visit("B") runs to completion before C is considered. Inside B, the search reaches D, which has no neighbors, so visit("D") returns at once. Control goes back to B, then back to A, which moves on to C. When C checks D, it finds D already visited and skips it.
Each solid arrow is a recursive call that actually ran. The skipped edge shows why the visited check matters. Without it, D would be visited twice here, and on a graph with a cycle the recursion would never stop.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Marking visited after the recursive calls | Infinite recursion on cycles | Call `visited.add(node)` first |
| Using `def visit(node, visited=set())` | State leaks between separate searches | Create the set inside the outer function |
| A vertex with no outgoing edges has no key | `KeyError` on `graph[node]` | Give every vertex a key, even with `[]` |
| A very long path | `RecursionError` | Raise the limit or use an explicit stack |
The order of each neighbor list matters too. DFS follows neighbors in the order they are listed, so the same graph with its lists reordered can give a different visit order. Both orders are valid depth-first traversals.
Exercise
Using dfs_recursive, what does the call print for graph = {"A": ["C", "B"], "B": ["D"], "C": ["D"], "D": []} starting at "A"?
Show answer
['A', 'C', 'D', 'B']. A visits C first, C visits D, and D has no neighbors, so control returns to A. A then visits B, and B skips D because D is already visited.
Exercise
Why does moving visited.add(node) to after the for loop break the function on the graph {"x": ["y"], "y": ["x"]}?
Show answer
visit("x") calls visit("y") before x is marked visited. y then sees x as unvisited and calls visit("x") again, so the two calls repeat until Python raises RecursionError.