Sub topic 11
Iterative DFS for Large Graphs
This chapter assumes you know three-color DFS for directed graphs and how to rebuild a cycle from parent pointers. Both were covered in earlier chapters. Here the same algorithm is rewritten so it no longer depends on Python's call stack.
Why Recursion Breaks on Large Graphs
A recursive DFS adds one stack frame for each vertex on the current path. CPython's default recursion limit is about 1000 frames. A dependency chain, a linked list stored as a graph, or a long path in a road network can easily be 100,000 vertices deep. On a graph like that, the recursive version raises RecursionError before it ever reaches a cycle.
Raising the limit with sys.setrecursionlimit hides the problem without fixing it. Python frames also use the C stack, and if that runs out the interpreter can crash with a segmentation fault instead of raising an exception you could catch. The safer fix is to keep the DFS path in a list on the heap.
Keeping an Iterator per Frame
When a recursive DFS returns from a child, it picks up the parent's neighbor loop exactly where it left off. An iterative version has to remember that position itself. The cleanest way is to store, for each vertex on the stack, an iterator over its neighbors. Each step looks at the top entry, pulls one more neighbor, and either goes deeper, records a back edge, or finishes the vertex.
The code below puts the iterative detector next to a recursive one and runs both on a 100,000-vertex cycle.
import sys
def has_cycle_recursive(adj):
color = [0] * len(adj)
def dfs(u):
color[u] = 1
for v in adj[u]:
if color[v] == 1 or (color[v] == 0 and dfs(v)):
return True
color[u] = 2
return False
return any(color[u] == 0 and dfs(u) for u in range(len(adj)))
def find_directed_cycle(adj):
n = len(adj)
color = [0] * n
parent = [-1] * n
for s in range(n):
if color[s]:
continue
color[s] = 1
stack = [(s, iter(adj[s]))]
while stack:
u, it = stack[-1]
v = next(it, None)
if v is None:
color[u] = 2
stack.pop()
elif color[v] == 0:
parent[v] = u
color[v] = 1
stack.append((v, iter(adj[v])))
elif color[v] == 1:
cycle = [v]
x = u
while x != v:
cycle.append(x)
x = parent[x]
cycle.append(v)
cycle.reverse()
return cycle
return None
n = 100_000
adj = [[i + 1] for i in range(n - 1)] + [[0]] # 0 -> 1 -> ... -> n-1 -> 0
try:
has_cycle_recursive(adj)
except RecursionError:
print("recursive: RecursionError")
cycle = find_directed_cycle(adj)
print("iterative:", len(cycle), cycle[:3], cycle[-1])Output:
recursive: RecursionError
iterative: 100001 [0, 1, 2] 0Common Mistakes
| Mistake | What goes wrong |
|---|---|
| Pushing all neighbors at once and popping one vertex at a time | No point marks when a vertex is finished, so you can't tell gray from black, and cross edges get reported as cycles. |
| Coloring a vertex gray when it is pushed rather than when it is entered | Vertices that are only waiting on the stack look like they are on the current path, which gives false positives. |
| Coloring black before all neighbors are used up | Real back edges into that vertex are missed. |
| Testing `if v` instead of `if v is None` with `next(it, None)` | Vertex `0` is falsy, so the vertex is treated as finished too early. |
The "push everything" style is fine for plain reachability or for undirected detection that tracks parent edges. Directed detection needs exact entry and exit times, and the iterator-per-frame stack is what supplies them.
Exercise
A colleague writes iterative directed DFS as: pop u, color it GRAY, push every WHITE neighbor, and report a cycle when a neighbor is GRAY. Give a small graph where this reports a false cycle.
Show answer
Edges 0→1, 0→2, 2→1. Pop 0 and color it gray, then push 1 and 2. Pop 2 and color it gray, then push 1 again because it is still white. Pop 1 and color it gray. Later, popping the duplicate 1 or checking 2→1 finds a gray vertex. The graph is acyclic, but no vertex is ever colored black, so the gray color stays on vertices that have already finished.
Exercise
Why does raising sys.setrecursionlimit to 10**6 not make the recursive version safe for a 100,000-vertex chain?
Show answer
Each Python frame also uses C stack memory. The operating system's thread stack (often 8 MB) can run out before Python's limit is reached, and that crashes the interpreter instead of raising a RecursionError you can catch.