Sub topic 5
Replacing Recursion with an Explicit Stack
This chapter assumes you have read the earlier chapters on adjacency lists, visited tracking, and recursive DFS. It also assumes you know how a call stack works and how a Python list behaves as a stack through append and pop.
Why Leave Recursion Behind
Recursive DFS is short, but each vertex on the current path takes up one frame on the call stack. CPython's default recursion limit is about 1000 frames. A graph shaped like a long chain, such as a linked list of 5,000 vertices or a maze with one winding corridor, raises RecursionError even though the graph itself is small.
You can avoid this by keeping your own stack in a list on the heap. The list grows with available memory, not with the interpreter's frame limit.
The Working Model
A recursive call says "explore this neighbor next, and come back to me later." A stack gives you the same last-in, first-out behavior. The vertex you pushed most recently is the next one you explore.
def dfs_iterative(graph, start):
visited = set()
order = []
stack = [start]
while stack:
node = stack.pop()
if node in visited:
continue
visited.add(node)
order.append(node)
# Push in reverse so neighbors are explored in listed order.
for neighbor in reversed(graph[node]):
if neighbor not in visited:
stack.append(neighbor)
return order
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(dfs_iterative(graph, "A")) # ['A', 'B', 'D', 'C']Two details make this match the recursive version:
- Reverse the push order. A stack pops the last item first. Pushing
Cand thenBmeansBcomes out first, which is the order the recursive loop would use. - Mark visited on pop, not on push. A vertex can be pushed more than once.
Dabove is reachable from bothBandC. Theif node in visited: continuecheck throws away stale copies.
Tracing the Stack
| Step | Popped | Order so far | Stack after pushes |
|---|---|---|---|
| 0 | none | [] | [A] |
| 1 | A | [A] | [C, B] |
| 2 | B | [A, B] | [C, D] |
| 3 | D | [A, B, D] | [C] |
| 4 | C | [A, B, D, C] | [] |
In step 4, C's neighbor D is already visited, so nothing is pushed.
Common Errors
Other mistakes to watch for:
- Forgetting to reverse. The traversal is still a valid DFS, but its order differs from the recursive version, so tests that expect a specific order fail.
- Expecting post-order for free. This loop only records discovery. To know when a vertex finishes, push a marker such as
(node, True)before its neighbors, and handle that marker when it is popped. - Using
list.pop(0). That removes from the front, which makes the list a queue and turns the search into BFS. It also costs O(n) per call.
Seeing the Depth Advantage
chain = {i: [i + 1] for i in range(5000)}
chain[5000] = []
print(len(dfs_iterative(chain, 0))) # 5001Running dfs_recursive on the same chain raises RecursionError under the default limit.
Exercise
Run dfs_iterative on graph = {"A": ["B", "C"], "B": [], "C": []} with the reversed() call removed, so neighbors are pushed in listed order. What order does it return, and why?
Show answer
['A', 'C', 'B']. A pushes B and then C. The stack pops the last item first, so C is explored before B. The result is still a valid DFS, but the neighbors are explored in reverse of their listed order.
Exercise
In the trace table, why can D appear on the stack while C is also waiting, and how many times can a vertex be pushed in the worst case?
Show answer
Vertices are only marked visited when popped, so a vertex can be pushed once for each edge that leads to it before it is popped. In the worst case a vertex is pushed once per incoming edge, so the stack can hold O(E) entries in total. The visited check on pop throws away the duplicates.