Sub topic 11
Iterative DFS for Large Graphs
This chapter assumes you know the recursive three-color DFS from the chapter on directed graphs and the parent-pointer cycle reconstruction from the previous chapter. You should also be comfortable with Python iterators and the next() built-in. The goal here is to get the same results without recursion, so that cycle detection keeps working on graphs with hundreds of thousands of vertices.
Why Recursion Breaks on Large Graphs
Recursive DFS keeps one Python stack frame alive for each vertex on the current path. The depth of the recursion equals the length of the longest path DFS follows, and that path can include every vertex in the graph. A linked chain of dependencies, a long linear pipeline, or a grid explored in snake order can all push the depth to V.
CPython's default recursion limit is 1000 frames. Once you pass it, the interpreter raises RecursionError:
WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle_directed(adj):
color = [WHITE] * len(adj)
def dfs(u):
color[u] = GRAY
for v in adj[u]:
if color[v] == GRAY:
return True
if color[v] == WHITE and dfs(v):
return True
color[u] = BLACK
return False
return any(color[u] == WHITE and dfs(u) for u in range(len(adj)))
n = 5000
path = [[i + 1] for i in range(n - 1)] + [[]] # 0 -> 1 -> ... -> 4999
try:
print(has_cycle_directed(path))
except RecursionError as e:
print("RecursionError:", e)The graph has no cycle and only 5000 vertices, yet the code fails before it can answer.
The setrecursionlimit trap
The obvious fix is sys.setrecursionlimit(10**6). That only raises Python's own counter. Each Python frame also uses space on the C stack of the thread, which is usually 1 to 8 MB. If you raise the limit far enough, the process can run out of C stack and crash with a segmentation fault. A crash gives no traceback and cannot be caught with except.
A common competitive-programming workaround runs the code in a thread with a larger stack:
import sys
import threading
def main():
n = 200_000
path = [[i + 1] for i in range(n - 1)] + [[]]
print(has_cycle_directed(path))
sys.setrecursionlimit(1 << 20)
threading.stack_size(512 * 1024 * 1024)
t = threading.Thread(target=main)
t.start()
t.join()This works on many systems, but it depends on the platform, it reserves a lot of memory, and you have to guess the right numbers. In library or production code, write the DFS iteratively.
The Naive Conversion and Why It Is Wrong
The textbook way to make DFS iterative is to pop a vertex, mark it, and push all of its neighbors. That is fine for reachability. For directed cycle detection it is wrong, because the colors depend on when a vertex finishes. A vertex must turn black only after all of its descendants are done. The push-all version has no moment that corresponds to "finished".
def has_cycle_naive(adj):
n = len(adj)
color = [0] * n
for s in range(n):
stack = [s]
while stack:
u = stack.pop()
if color[u]:
continue
color[u] = 1 # gray, but never becomes black
for v in adj[u]:
if color[v] == 1:
return True
stack.append(v)
return False
diamond = [[1, 2], [3], [3], []] # 0->1, 0->2, 1->3, 2->3: acyclic
print(has_cycle_naive(diamond)) # True (wrong)Vertex 3 is reached through 2 and stays gray. When 1 is processed later, its edge to 3 looks like a back edge, even though 3 is not on the current path. The diamond is a DAG, so this answer is a false positive.
Changing it to "mark black after pushing the neighbors" does not help. The neighbors have not been explored yet at that point, so a real back edge to u would then be missed.
Simulating the Call Stack Exactly
The correct conversion stores what a recursive frame stores: the vertex, plus how far along its neighbor list the loop has got. A Python iterator over adj[u] holds that position. Each loop step looks at the top frame and advances its iterator by one neighbor:
- If the iterator is exhausted, the vertex is finished. Color it black and pop the frame. This matches a recursive call returning.
- If the neighbor is white, record its parent, color it gray, and push a new frame. This matches a recursive call.
- If the neighbor is gray, the edge is a back edge, which means a cycle.
- If the neighbor is black, ignore it.
Here is the full implementation. It also rebuilds the cycle with parent pointers, as described in the previous chapter:
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
diamond = [[1, 2], [3], [3], []]
print(find_directed_cycle(diamond)) # None
triangle = [[1], [2], [0]]
print(find_directed_cycle(triangle)) # [0, 1, 2, 0]
self_loop = [[0]]
print(find_directed_cycle(self_loop)) # [0, 0]
n = 200_000
path = [[i + 1] for i in range(n - 1)] + [[]]
print(find_directed_cycle(path)) # None, no RecursionError
ring = [[(i + 1) % n] for i in range(n)]
print(len(find_directed_cycle(ring))) # 200001The stack holds exactly the gray vertices, in path order. That invariant is what makes the gray test mean "on the current path", the same as in the recursive version.
Details that matter
The sentinel. next(it, None) returns None when the iterator is exhausted. This is safe because vertices are integers. If your vertex labels could include None, create a private sentinel with _END = object() and compare with is.
Marking gray on push. A vertex turns gray when its frame is pushed, not when it is first seen as a neighbor. The stack never holds duplicate frames, so total work stays at O(V + E).
The outer loop. The for s in range(n) loop restarts DFS from every white vertex, which covers disconnected graphs. Black vertices from earlier trees are skipped correctly. An edge into an earlier tree is a cross edge, not a cycle.
Index-Based Frames
Iterator objects are convenient, but each one is a heap allocation. An alternative stores an integer position per vertex and uses plain lists:
def has_cycle_directed_iter(adj):
n = len(adj)
color = [0] * n
pos = [0] * n
for s in range(n):
if color[s]:
continue
color[s] = 1
stack = [s]
while stack:
u = stack[-1]
if pos[u] < len(adj[u]):
v = adj[u][pos[u]]
pos[u] += 1
if color[v] == 0:
color[v] = 1
stack.append(v)
elif color[v] == 1:
return True
else:
color[u] = 2
stack.pop()
return False
print(has_cycle_directed_iter([[1, 2], [3], [3], []])) # False
print(has_cycle_directed_iter([[1], [2], [0]])) # True| Approach | Max depth | Extra memory | Notes |
|---|---|---|---|
| Recursive | about 1000 by default | one Python frame per vertex on the path | shortest code, fails on long paths |
| Recursive with big thread stack | set by you | large reserved stack | depends on the platform, crashes if the guess is too small |
| Iterative, iterator frames | limited by RAM | one tuple and iterator per path vertex | readable, mirrors recursion closely |
| Iterative, index array | limited by RAM | one int per vertex | lowest overhead, easy to port to C or Rust |
Undirected Graphs
For undirected detection, the earlier has_cycle_undirected was already iterative, and the naive push-all style works there. An undirected graph has no forward or cross edges, so any non-tree edge to a visited vertex closes a cycle. Finish order does not matter. Only the edge you arrived by must be skipped, which is why that code stores parent_edge with each stack entry. The frame-simulation technique is needed only when the algorithm cares about finish time, as directed three-color DFS does.
Common Errors
| Mistake | Symptom |
|---|---|
| Pop-and-push-all with gray/black colors | false cycles on DAGs such as diamonds |
| Coloring black right after pushing neighbors | real cycles missed |
| Marking gray when a vertex is pushed in push-all style | duplicate frames and wrong parents |
| Using `None` as a sentinel when `None` is a valid label | early termination of a frame |
| Restarting DFS only from vertex 0 | cycles in other components missed |
Exercise
In hascyclenaive, vertex 3 of the diamond was wrongly treated as a back-edge target. Trace finddirectedcycle on the diamond [[1, 2], [3], [3], []] and give the color of vertex 3 at the moment the edge 2 -> 3 is examined. Why does this prevent the false positive?
Show answer
DFS pushes 0, then 1, then 3. Vertex 3 has no neighbors, so it turns black and is popped. Then 1 is exhausted, turns black, and is popped. Back at 0, the next neighbor is 2, which is pushed. When 2 examines the edge to 3, vertex 3 is black, so the edge is skipped. Black means "fully explored and not on the current path". The iterative version reaches that state exactly when the recursive call would return, which the naive version never does.
Exercise
Modify hascycledirected_iter so that it returns the cycle as a vertex list, starting and ending at the same vertex, instead of True.
Show answer
Add parent = [-1] * n. When a white v is pushed, set parent[v] = u. When color[v] == 1, build cycle = [v], walk x = u through parent appending each x until x == v, append v, reverse the list, and return it. Return None at the end instead of False. The stack already holds the path, so another option is to slice it: cycle = stack[stack.index(v):] + [v]. That slice costs O(path length) to find v.
Exercise
A graph has 10^6 vertices forming one directed path. Estimate the peak stack length for the iterative DFS, and explain why the recursive version would fail even with sys.setrecursionlimit(2000000) on a default 8 MB thread stack.
Show answer
The peak stack length is 10^6 frames, one per vertex, all stored on the heap. A recursive CPython call uses at least hundreds of bytes of C stack per frame, and often more. A million frames need hundreds of megabytes, far more than 8 MB, so the process overflows the C stack and segfaults before Python's own limit is reached.