Sub topic 5
Replacing Recursion with an Explicit Stack
This chapter assumes you have read the previous chapter on recursive DFS. You should be comfortable with Python lists, sets, and dictionaries, and you should know how the call stack works during recursion. The examples use the same adjacency-list dictionaries as earlier chapters.
Recursive DFS is short and easy to read, but it hands all of its bookkeeping to the language runtime. Each call to visit pushes a frame onto the call stack. That frame holds the current vertex and remembers how far the loop over its neighbors has progressed. An iterative DFS keeps this information in a data structure you control, usually a plain Python list used as a stack. The traversal logic does not change. The stack just moves from the runtime into your own code.
Why Leave Recursion Behind
The main practical reason is depth. CPython limits recursion to 1000 frames by default (sys.getrecursionlimit()), and a DFS goes as deep as the longest path it follows. A linked chain of a few thousand vertices, or a long winding corridor in a maze grid, is enough to crash a recursive traversal.
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
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
n = 5000
path = {i: [i + 1] for i in range(n - 1)}
path[n - 1] = []
try:
dfs_recursive(path, 0)
except RecursionError:
print("recursive version: RecursionError")
print("iterative version visited", len(dfs_iterative(path, 0)), "vertices")You can raise the limit with sys.setrecursionlimit, but that only postpones the problem. The C stack under the interpreter can still overflow and kill the process without a clean Python exception. An explicit stack lives on the heap, so the only limit is available memory.
Other reasons to go iterative:
- You can pause, resume, or inspect the traversal, for example to step through it in a visualizer or to stop early without unwinding many frames.
- Some languages and environments, such as embedded code or GPU kernels, restrict or forbid deep recursion.
- The state is visible. You can print the stack and see exactly which vertices are waiting.
How the Explicit Stack Works
The loop repeats one step: pop a vertex, and if it has not been visited, mark it, record it, and push its unvisited neighbors. Because a stack is last-in, first-out, the most recently pushed neighbor is explored next. That is what makes the traversal go deep before it goes wide.
Two details deserve attention.
Reversed push order. The recursive version explores neighbors in list order: for "A": ["B", "C"] it visits B first. A stack returns items in the opposite order from how they went in. Pushing reversed(graph[node]) puts B on top, so B is popped first and the iterative output matches the recursive one.
Visited check on pop. A vertex can be pushed more than once if several already-visited vertices list it as a neighbor. The if node in visited: continue line throws away these stale copies. The if neighbor not in visited test before pushing is only an optimization. The check on pop is the one that keeps the algorithm correct.
Here is the trace for the graph {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}:
| Step | Popped | Action | Stack after (top on right) | Order so far |
|---|---|---|---|---|
| 1 | A | visit, push C, B | [C, B] | A |
| 2 | B | visit, push D | [C, D] | A, B |
| 3 | D | visit, no neighbors | [C] | A, B, D |
| 4 | C | visit, D already visited | [] | A, B, D, C |
The Mark-on-Push Trap
A common "optimization" marks vertices as visited when they are pushed instead of when they are popped. That version never puts duplicates on the stack, but it stops being depth-first. Once a vertex is marked, a deeper path can no longer claim it, so it stays attached to the shallower vertex that pushed it.
def dfs_mark_on_push(graph, start):
visited = {start}
order = []
stack = [start]
while stack:
node = stack.pop()
order.append(node)
for neighbor in reversed(graph[node]):
if neighbor not in visited:
visited.add(neighbor)
stack.append(neighbor)
return order
def dfs_mark_on_pop(graph, start):
visited = set()
order = []
stack = [start]
while stack:
node = stack.pop()
if node in visited:
continue
visited.add(node)
order.append(node)
for neighbor in reversed(graph[node]):
if neighbor not in visited:
stack.append(neighbor)
return order
graph = {"A": ["B", "C"], "B": ["C", "D"], "C": [], "D": []}
print(dfs_mark_on_pop(graph, "A")) # ['A', 'B', 'C', 'D'] true DFS order
print(dfs_mark_on_push(graph, "A")) # ['A', 'B', 'D', 'C'] not DFS orderReal DFS reaches C through B, because B lists C first. The mark-on-push version marks C while processing A, so B skips it, and C comes out last. If all you need is the set of reachable vertices, both versions are fine. For anything that depends on DFS structure, such as parent pointers, finish times, or edge types, the mark-on-push version gives wrong answers.
Faithful Simulation with Neighbor Iterators
The pop-based loop finishes processing a vertex as soon as it pushes that vertex's neighbors. It has no moment that matches "the recursive call returns," so it cannot report when a vertex finishes. Later chapters need finish times for cycle detection and topological sort, and those require a closer copy of the call stack.
The fix is to store what a recursive frame stores: the vertex plus a cursor into its neighbor list. A Python iterator works well as that cursor.
def dfs_with_iterators(graph, start):
visited = {start}
preorder = [start]
postorder = []
stack = [(start, iter(graph[start]))]
while stack:
node, neighbors = stack[-1]
for neighbor in neighbors:
if neighbor not in visited:
visited.add(neighbor)
preorder.append(neighbor)
stack.append((neighbor, iter(graph[neighbor])))
break # descend now; resume this iterator later
else:
stack.pop() # neighbors exhausted: node finishes
postorder.append(node)
return preorder, postorder
graph = {"A": ["B", "C"], "B": ["C", "D"], "C": [], "D": []}
print(dfs_with_iterators(graph, "A"))
# (['A', 'B', 'C', 'D'], ['C', 'D', 'B', 'A'])In this version, marking on push is correct, because a pushed vertex goes on top of the stack and is processed right away, exactly like a recursive call. The for ... else clause runs only when the loop ends without break, which means every neighbor has been checked. You do not need reversed either, because the iterator walks the neighbors in their listed order.
Comparing the Variants
| Variant | Matches recursive preorder | Gives finish order | Maximum stack size |
|---|---|---|---|
| Mark on pop | Yes, with reversed push | No | O(E), duplicates allowed |
| Mark on push | No | No | O(V) |
| Neighbor iterators | Yes | Yes | O(V), one entry per vertex on the current path |
All three run in O(V + E) time on an adjacency list. The next chapter explains why. The space difference matters on dense graphs: the mark-on-pop stack can hold one entry per edge, while the iterator stack never holds more than the length of the current path.
Common Errors
- Forgetting
reversed, which produces a valid DFS that explores neighbors right to left. Your tests will fail if they expect the recursive order. - Dropping the visited check on pop in the mark-on-pop version, which visits vertices more than once.
- Using
list.pop(0), which takes from the front of the list, so the traversal turns into a slow breadth-first search. - Recording finish times at pop time in the simple loop. At that point the vertex's descendants have not been explored yet.
Exercise
Run dfs_iterative (mark on pop, reversed push) on {"A": ["B", "C", "D"], "B": ["D"], "C": [], "D": ["C"]} starting at "A". List the stack after each pop and give the final visit order.
Show answer
Pop A, push D, C, B: stack [D, C, B]. Pop B, push D: [D, C, D]. Pop D, push C: [D, C, C]. Pop C, nothing to push: [D, C]. Pop C, already visited: [D]. Pop D, already visited: []. Visit order: A, B, D, C, the same as recursive DFS.
Exercise
Change dfswithiterators so it also returns a parent dictionary that maps each discovered vertex to the vertex it was discovered from, with the start vertex mapped to None. What is the parent map for graph {"A": ["B", "C"], "B": ["C", "D"], "C": [], "D": []}?
Show answer
Initialize parent = {start: None}, and set parent[neighbor] = node in the same place as visited.add(neighbor). The result is {"A": None, "B": "A", "C": "B", "D": "B"}. C's parent is B, not A, which confirms the traversal is truly depth-first.