Sub topic 13
Avoiding Recursion Limits with Iterative DFS
Both SCC algorithms from earlier chapters are written recursively. That works on textbook examples, but it breaks on real inputs. A dependency graph with 100,000 modules, or a 2-SAT instance with a long chain of implications, can produce a DFS path thousands of vertices deep. CPython caps recursion at 1,000 frames by default, so the recursive versions crash with RecursionError well before they reach any time limit.
This chapter shows how to replace the call stack with an explicit stack of your own. It assumes you have read the chapters on DFS finish times, Kosaraju's algorithm, and Tarjan's low-link values, and that you can read Python comfortably.
Why Recursion Fails on Large Graphs
DFS recursion depth equals the length of the longest path the search follows. Graph size alone doesn't decide this. A graph with a million vertices and short paths is fine. A simple chain 0 → 1 → 2 → … → 1999 fails.
def depth_first(u, adj, seen):
seen[u] = True
for v in adj[u]:
if not seen[v]:
depth_first(v, adj, seen)
n = 2000
chain = [[i + 1] for i in range(n - 1)] + [[]]
try:
depth_first(0, chain, [False] * n)
print("finished")
except RecursionError:
print("RecursionError on a chain of", n, "vertices")The `setrecursionlimit` workaround and its risks
A common quick fix is sys.setrecursionlimit(10**6). That raises Python's counter, but the interpreter still needs native stack memory for each frame on many builds and versions. With a high limit and a deep graph, the process can die with a segmentation fault instead of a catchable exception. People often pair the limit with threading.stack_size(...) and run the search in a new thread. That can work, but it depends on the platform and is fragile.
The Core Idea: Frames You Manage Yourself
A recursive call stores two things that matter to DFS: which vertex it is processing, and how far it has got through that vertex's adjacency list. An iterative DFS stores exactly that as a tuple (vertex, next_edge_position) on a list used as a stack.
| Recursive construct | Iterative equivalent |
|---|---|
| Calling `dfs(w)` | Push frame `(w, 0)` |
| Loop variable inside `for v in adj[u]` | Edge position `i` stored in the frame |
| Returning from `dfs(w)` | Popping `w`'s frame once `i == len(adj[w])` |
| Code after the recursive call (e.g. `low[v] = min(low[v], low[w])`) | Run on the parent frame right after the child's frame is popped |
| Code after the loop (e.g. recording finish time) | Run when the frame's edges are exhausted |
The last two rows cause most bugs. Recursion runs "after the call" code automatically. In an iterative version you have to work out where that code goes.
Iterative Kosaraju
The first pass of Kosaraju's algorithm needs true finish order: a vertex is recorded only after every vertex reachable from it through unvisited paths has been recorded. The second pass only labels whatever it can reach in the transpose, so any traversal order works there, including a plain stack without frames.
def kosaraju_iterative(n, adj):
visited = [False] * n
order = []
for s in range(n):
if visited[s]:
continue
visited[s] = True
work = [(s, 0)]
while work:
v, i = work[-1]
if i < len(adj[v]):
work[-1] = (v, i + 1) # remember progress in v's list
w = adj[v][i]
if not visited[w]:
visited[w] = True
work.append((w, 0)) # "recursive call"
else:
work.pop()
order.append(v) # finish time of v
radj = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
radj[v].append(u)
comp = [-1] * n
c = 0
for s in reversed(order): # decreasing finish time
if comp[s] != -1:
continue
comp[s] = c
stack = [s]
while stack: # order is irrelevant here
u = stack.pop()
for v in radj[u]:
if comp[v] == -1:
comp[v] = c
stack.append(v)
c += 1
return comp
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
print(kosaraju_iterative(8, adj)) # [1, 1, 1, 2, 2, 2, 0, 0]This matches the recursive version's output from the Kosaraju chapter, including component numbers, because both visit edges in the same order.
The "push all neighbors" trap
The textbook iterative DFS pops a vertex, marks it, and pushes all of its neighbors at once. It visits the right set of vertices, but the order in which vertices are popped is a preorder, not a finish order. If you append to order at pop time in that style, the first pass of Kosaraju gives wrong components on many graphs. Frames with edge positions are the simplest way to know exactly when a vertex finishes.
Iterative Tarjan
Tarjan's algorithm has two kinds of "after" work: updating the parent's low-link once a child returns, and popping an SCC when a vertex's edges run out. The version below handles both.
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
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
print(tarjan_iterative(8, adj)) # [[5, 4, 3], [2, 1, 0], [7, 6]]Details that make it correct
- Parent frame ordering. When
wis discovered,(v, i + 1)is pushed before(w, 0). Whenw's frame later finishes,work[-1]is thereforev's frame. That is how the code finds the DFS parent without storing it. - Low-link propagation after the SCC check. If
vjust closed its own component, thenlow[v] == index[v] > index[parent], so theminleaves the parent unchanged. Running the update unconditionally is safe. - Two different stacks.
workimitates the call stack.stackis Tarjan's component stack. A vertex leavesworkwhen it finishes but can stay onstacklong after, until its component's root pops it. Merging the two is a common mistake. - Self-loops and isolated vertices. A self-loop
v → vseeson_stack[v]true and setslow[v] = min(low[v], index[v]), which changes nothing. An isolated vertex finishes immediately and forms a singleton SCC.
Stress Testing Deep Graphs
Run this in the same file as the two functions above. A single cycle through 200,000 vertices forces a DFS path 200,000 deep. A chain of the same length has no cycles, so every vertex is its own SCC.
n = 200_000
big_cycle = [[i + 1] for i in range(n - 1)] + [[0]]
assert len(set(kosaraju_iterative(n, big_cycle))) == 1
sccs = tarjan_iterative(n, big_cycle)
assert len(sccs) == 1 and len(sccs[0]) == n
chain = [[i + 1] for i in range(n - 1)] + [[]]
assert len(set(kosaraju_iterative(n, chain))) == n
assert len(tarjan_iterative(n, chain)) == n
print("deep graphs handled without recursion")Cost of the Conversion
Each vertex's frame is pushed once at discovery. Each edge causes one frame update (Kosaraju) or one pop-and-push (Tarjan). Total time stays O(V + E). The work list holds at most one frame per vertex on the current DFS path, so it uses O(V) memory in the worst case, the same as the recursion depth it replaces. Tuples on a Python list are much smaller than interpreter frames, and running out of heap memory is far less likely than running out of call stack.
| Concern | Recursive | Iterative with frames |
|---|---|---|
| Max depth before failure | about 1,000 by default | limited by heap memory |
| Failure mode on deep input | `RecursionError` or segfault | none in practice |
| Readability | closer to the proofs | more bookkeeping |
| Time complexity | O(V + E) | O(V + E) |
Exercise
A colleague writes Kosaraju's first pass as: push s; while the stack is non-empty, pop u, skip it if visited, mark it visited, append u to order, then push all unvisited neighbors. Why can this give wrong SCCs, and what is the minimal fix?
Show answer
The vertex is appended when it is first popped, which is a discovery (preorder) position, not its finish time. A vertex can then appear in order before vertices reachable from it, which breaks the decreasing-finish-time guarantee the second pass depends on. The fix is to keep (vertex, edge position) frames and append u only when its edge position reaches len(adj[u]), meaning all of its descendants have finished.
Exercise
In tarjan_iterative, suppose the two lines were swapped so that (w, 0) is pushed before (v, i + 1). What breaks?
Show answer
The next frame popped would be (v, i + 1) instead of w's frame, so v would keep scanning edges before w had been explored. Also, when w eventually finishes, work[-1] would no longer be v's frame, so the low-link update would go to the wrong vertex. The order of the pushes is what encodes the parent-child relationship.
Exercise
On the graph adj = [[0, 1], [0]] (a self-loop on 0 and a 2-cycle between 0 and 1), what does tarjan_iterative(2, adj) return?
Show answer
[[1, 0]]. Vertex 0 gets index 0, and its self-loop leaves low[0] at 0. Vertex 1 gets index 1, and its edge back to 0 (on the stack) sets low[1] = 0. When 1 finishes, low[1] != index[1], so nothing is popped, and low[0] stays 0. When 0 finishes, low[0] == index[0], so it pops 1 and then 0, giving the single component [1, 0].