Sub topic 10
Recovering the Cycle Itself
This chapter assumes you know three-color DFS for directed graphs and parent tracking for undirected graphs from the earlier chapters. It also assumes you can read recursive Python.
A yes-or-no answer is often not enough. A build tool that finds a circular dependency should tell the user which packages form the loop. Getting that list is cheap, because DFS already knows the path it is on. You only need to write it down.
The Idea: Parent Pointers Record the Current Path
When DFS moves from u to an unvisited vertex v, store parent[v] = u. At any moment, the gray vertices are the DFS path from the root to the current vertex. Following parent from the current vertex walks back along that path.
In a directed graph, a cycle shows up as a back edge u → v, where v is gray. Since v is gray, it is an ancestor of u on the current path. So the cycle is:
v, then the tree path fromvdown tou,- then the back edge
u → v, which closes the loop.
You build the cycle by starting at u, following parent until you reach v, and reversing the result.
Directed Implementation
def find_directed_cycle(adj):
n = len(adj)
color = [0] * n # 0 white, 1 gray, 2 black
parent = [-1] * n
def dfs(u):
color[u] = 1
for v in adj[u]:
if color[v] == 0:
parent[v] = u
found = dfs(v)
if found:
return found
elif color[v] == 1:
cycle = [v]
x = u
while x != v:
cycle.append(x)
x = parent[x]
cycle.append(v)
cycle.reverse()
return cycle
color[u] = 2
return None
for s in range(n):
if color[s] == 0:
found = dfs(s)
if found:
return found
return None
adj = [[1], [2], [3], [1], []] # 0->1->2->3->1
print(find_directed_cycle(adj)) # [1, 2, 3, 1]
print(find_directed_cycle([[0]])) # [0, 0] self-loop
print(find_directed_cycle([[1], []])) # NoneThe returned list starts and ends at the same vertex. Vertex 0 is not in the output. It is on the DFS path, but it comes before v, so it is not part of the loop.
Undirected Graphs
The same walk works in an undirected graph if you use true recursive DFS with parent-edge tracking. With that DFS, the first non-parent edge u — v that reaches a visited vertex always points to an ancestor of u. Following parent from u up to v then gives the cycle. Two parallel edges between u and v give [u, v, u], a cycle of length 2, and a self-loop gives [u, u].
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Walking `parent` until `-1` | Output includes vertices before the loop | Stop when you reach `v` |
| Forgetting to append `v` again | The cycle does not close | Add `v` at both ends |
| Not reversing | Cycle listed against edge direction | Reverse after collecting |
| Setting `parent` on gray or black hits | Corrupted path | Set `parent` only on white vertices |
Exercise
For adj = [[1], [2], [0, 3], []], what does finddirectedcycle return, and why is vertex 3 absent?
Show answer
It returns [0, 1, 2, 0]. DFS goes 0 → 1 → 2, then finds edge 2 → 0 to a gray vertex. Walking parents from 2 gives 2, 1, and stops at 0. Vertex 3 is never reached before the cycle is found, and it is not on any cycle anyway.
Exercise
Why can the walk from u along parent pointers never miss v in the directed version?
Show answer
The vertex v is gray, which means it is on the current root-to-u DFS path. Parent pointers trace exactly that path backward from u, so the walk must reach v before it reaches the root.