Sub topic 3
Recovering the Cycle Itself
This chapter assumes you know three-color DFS (white, gray, black), Kahn's algorithm, and Big-O notation. It covers how to recover the cycle you detected, how to scale DFS to large graphs, a special case for functional graphs, and how to pick a method.
Recovering the Cycle from Parent Pointers
A detector that only answers yes or no rarely helps in practice. Users want to see the cycle. To get it, record parent[v] = u each time DFS discovers v from u. Suppose you then find a back edge u → v, where v is gray. Walking parent pointers from u back to v traces the cycle.
Iterative DFS for Large Graphs
CPython's default recursion limit is 1000 frames. A path of 10,000 vertices makes recursive DFS crash with RecursionError. The fix is an explicit stack of (vertex, neighbor iterator) pairs. The stack keeps each vertex's place in its neighbor list, just as a recursive call frame would.
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
print(find_directed_cycle([[1], [2], [0]])) # [0, 1, 2, 0]Functional Graphs and Floyd's Tortoise and Hare
In a functional graph, every vertex has exactly one outgoing edge, x → f(x). Any walk through it ends in a cycle. Floyd's algorithm finds mu, the index where the cycle starts, and lam, the cycle's length, using O(1) extra memory.
def floyd_cycle(f, x0):
tortoise, hare = f(x0), f(f(x0))
while tortoise != hare:
tortoise, hare = f(tortoise), f(f(hare))
mu, tortoise = 0, x0
while tortoise != hare:
tortoise, hare = f(tortoise), f(hare)
mu += 1
lam, hare = 1, f(tortoise)
while tortoise != hare:
hare = f(hare)
lam += 1
return mu, lam
nxt = {0: 1, 1: 2, 2: 3, 3: 4, 4: 2}
print(floyd_cycle(nxt.__getitem__, 0)) # (2, 3)Strongly Connected Components as Cyclic Regions
A strongly connected component (SCC) is a maximal set of vertices where each vertex can reach every other one. Every directed cycle lies inside a single SCC. An SCC with more than one vertex always contains a cycle, and so does a single vertex with a self-loop. Tarjan's and Kosaraju's algorithms find all SCCs in O(V + E) time. That reports every cyclic region in the graph, where the code above stops at the first cycle.
Complexity and Choosing the Right Method
| Situation | Method | Cost |
|---|---|---|
| Undirected, static | DFS with parent edge | O(V + E) |
| Undirected, edges arrive over time | Union-find | Near O(1) per edge, amortized |
| Directed, need the cycle | Three-color DFS | O(V + E) |
| Directed, need an order | Kahn's algorithm | O(V + E) |
| One successor per vertex | Floyd | O(mu + lam) time, O(1) space |
Where Cycle Detection Is Used
- Package managers and build systems: they run a topological sort and reject circular dependencies, showing the cycle in the error message.
- Deadlock detection: a cycle in a wait-for graph means a set of threads are each waiting on another thread in the set.
- Spreadsheets: they flag a formula that depends on its own cell, directly or through other cells.
Exercise
Kahn's algorithm reports a cycle, and your users need the cycle's vertices. What do you run, and on which vertices?
Show answer
Run three-color DFS with parent pointers, such as finddirectedcycle, on the subgraph of vertices Kahn never removed. Every vertex Kahn left behind lies on a cycle or downstream of one, so DFS from them will find a back edge and recover the cycle.