Sub topic 13
Avoiding Recursion Limits with Iterative DFS
This chapter assumes you know the recursive versions of Kosaraju's and Tarjan's algorithms from earlier chapters, and that you understand how a call stack holds the local state of each function call.
Why recursion breaks on real graphs
Both SCC algorithms make one recursive call for each tree edge of the DFS. On a long path such as 0 → 1 → 2 → … → n-1, the recursion depth reaches n. CPython stops at a default limit of 1000 frames and raises RecursionError. Raising the limit with sys.setrecursionlimit only moves the problem. Each Python frame also uses the C stack, so a large enough limit can crash the interpreter with a segmentation fault instead of a clean error.
The reliable fix is to keep the DFS state in a list you control. Lists live on the heap, so their size is limited only by memory.
What a stack frame must remember
A recursive call to strongconnect(v) holds two pieces of state while it is paused:
- the vertex
v - how far it has got through
adj[v]
The iterative version stores exactly this pair, (v, i), on an explicit work stack. Each time a frame is popped, it either looks at one more edge or, if no edges remain, finishes the vertex.
Iterative Tarjan
def tarjan_iterative(n, adj):
index = [-1] * n
low = [0] * n
on_stack = [False] * n
stack = []
sccs = []
counter = 0
for root in range(n):
if index[root] != -1:
continue
index[root] = low[root] = counter
counter += 1
stack.append(root)
on_stack[root] = True
work = [(root, 0)] # (vertex, next edge position)
while work:
v, i = work.pop()
if i < len(adj[v]):
w = adj[v][i]
work.append((v, i + 1))
if index[w] == -1:
index[w] = low[w] = counter
counter += 1
stack.append(w)
on_stack[w] = True
work.append((w, 0))
elif on_stack[w]:
low[v] = min(low[v], index[w])
else:
if low[v] == index[v]:
comp = []
while True:
w = stack.pop()
on_stack[w] = False
comp.append(w)
if w == v:
break
sccs.append(comp)
if work:
parent = work[-1][0]
low[parent] = min(low[parent], low[v])
return sccs
n = 200_000
path = [[i + 1] for i in range(n - 1)] + [[]]
print(len(tarjan_iterative(n, path))) # 200000, no RecursionErrorThe line low[parent] = min(low[parent], low[v]) replaces the code that ran after the recursive call returned. It works because the frame (v, i+1) was pushed under (w, 0), so when w finishes, its parent sits on top of the work stack.
Iterative Kosaraju
Kosaraju's first pass needs correct finish times, so it uses the same (v, i) frames and appends v to order when its edges run out. The second pass only labels whatever it can reach on the transpose, and the order of visits does not matter there. A plain stack that pushes every unvisited neighbor is enough for that pass.
Common errors
| Mistake | Effect |
|---|---|
| Pushing all neighbors at once in pass 1 of Kosaraju | Vertices "finish" in the wrong order, so components merge |
| Marking visited when popping instead of when pushing | A vertex is pushed twice and gets two indices |
| Forgetting the low-link update to the parent | Roots are detected too early, so SCCs split into pieces |
| Pushing `(v, i+1)` after `(w, 0)` | The parent is processed before its child finishes |
Exercise
In tarjan_iterative, why is it safe to read the parent as work[-1][0] right after vertex v finishes, and what breaks if you swap the order of work.append((v, i + 1)) and work.append((w, 0))?
Show answer
Before descending into w, the code pushes the parent's resume frame (v, i+1) and then (w, 0) on top of it. While w's subtree is explored, frames are pushed above (v, i+1) and popped off again, so when w finishes the frame on top belongs to its parent. If you swap the two pushes, (v, i+1) is popped first. The parent then keeps scanning edges, and can even finish, before w has been explored. Low-link values stop propagating correctly, and the parent read when w finishes may be the wrong vertex.