Sub topic 10
Recovering the Cycle Itself
Earlier chapters answered a yes-or-no question: does this graph contain a cycle? In practice a plain yes is rarely enough. A build tool that finds a dependency loop has to tell you which packages form the loop. A deadlock detector has to name the threads that are waiting on each other. This chapter shows how to turn a detected cycle into a concrete list of vertices, using the parent pointers that DFS already gives you.
This chapter assumes you know three-color DFS for directed graphs and parent-edge DFS for undirected graphs from the earlier chapters. You should also be able to read recursive Python and know what a DFS tree is.
The Idea: The Recursion Stack Is the Cycle
When DFS finds a cycle, the cycle is already sitting in its state. Take three-color DFS. A gray vertex is one whose call has started but not finished, so the gray vertices are exactly the vertices on the current recursion path from the root to the vertex being explored. A back edge u -> v, where v is gray, means v is an ancestor of u on that path. The cycle is the tree path from v down to u, followed by the edge u -> v back to the start.
To recover that path, record a parent pointer whenever DFS discovers a vertex: parent[child] = u. Then start at u and follow parent pointers upward until you reach v.
The walk has to stop at v and not at the DFS root. In the diagram the root is 0, but 0 is not on the cycle. If you keep walking to the root, you get a path that leads into the cycle, which is not a cycle.
Directed Graphs: Three-Color DFS with Parents
Here is the three-color DFS from the directed-graph chapter, extended to keep parent pointers and return the cycle.
WHITE, GRAY, BLACK = 0, 1, 2
def find_cycle_directed(adj):
n = len(adj)
color = [WHITE] * n
parent = [-1] * n
def build_cycle(u, v):
# Back edge u -> v; v is an ancestor of u on the DFS path.
cycle = [v]
x = u
while x != v:
cycle.append(x)
x = parent[x]
cycle.append(v)
cycle.reverse()
return cycle
def dfs(u):
color[u] = GRAY
for v in adj[u]:
if color[v] == GRAY:
return build_cycle(u, v)
if color[v] == WHITE:
parent[v] = u
found = dfs(v)
if found:
return found
color[u] = BLACK
return None
for s in range(n):
if color[s] == WHITE:
found = dfs(s)
if found:
return found
return None
if __name__ == "__main__":
adj = [[1], [2], [3], [1]] # 0 -> 1 -> 2 -> 3 -> 1
print(find_cycle_directed(adj)) # [1, 2, 3, 1]
print(find_cycle_directed([[0]])) # [0, 0] (self-loop)
print(find_cycle_directed([[1], [2], []])) # NoneTracing the Walk
For adj = [[1], [2], [3], [1]], DFS goes 0, 1, 2, 3 and sets parent[1] = 0, parent[2] = 1, parent[3] = 2. At vertex 3 it sees edge 3 -> 1, and 1 is gray.
| Step | `x` | `cycle` after append |
|---|---|---|
| start | 3 | `[1]` |
| append `x`, move to `parent[3]` | 2 | `[1, 3]` |
| append `x`, move to `parent[2]` | 1 | `[1, 3, 2]` |
| `x == v`, append `v` | 1 | `[1, 3, 2, 1]` |
| reverse | `[1, 2, 3, 1]` |
The walk collects vertices backward, from u up toward v. Reversing puts them in edge order, so each consecutive pair (cycle[i], cycle[i+1]) is an edge of the graph.
Why the Parent Chain Is Trustworthy
Two facts make the walk correct:
- A vertex gets a parent only once, at the moment it turns from white to gray. Later edges into it never overwrite the pointer, so the chain from
ufollows the actual recursion path. - Every vertex on the current path is gray, and
vis on that path. Following parents fromutherefore reachesvbefore it reaches the root, and the loop ends.
The loop visits each cycle vertex once, so reconstruction costs O(k) for a cycle of length k. That is at most O(V) on top of the O(V + E) search.
Undirected Graphs: Parent-Edge DFS with Parents
The undirected version follows the same plan, but it skips the edge used to reach each vertex, identified by edge index so that parallel edges stay distinct. When a vertex u finds an already-visited neighbor v through a different edge, it walks parent pointers from u to v.
def find_cycle_undirected(n, edges):
adj = [[] for _ in range(n)]
for i, (a, b) in enumerate(edges):
adj[a].append((b, i))
adj[b].append((a, i))
visited = [False] * n
parent = [-1] * n
def dfs(u, parent_edge):
visited[u] = True
for v, eid in adj[u]:
if eid == parent_edge:
continue
if visited[v]:
cycle = [v]
x = u
while x != v:
cycle.append(x)
x = parent[x]
cycle.append(v)
cycle.reverse()
return cycle
parent[v] = u
found = dfs(v, eid)
if found:
return found
return None
for s in range(n):
if not visited[s]:
found = dfs(s, -1)
if found:
return found
return None
if __name__ == "__main__":
print(find_cycle_undirected(4, [(0, 1), (1, 2), (2, 3), (3, 1)])) # [1, 2, 3, 1]
print(find_cycle_undirected(2, [(0, 1), (0, 1)])) # [0, 1, 0]
print(find_cycle_undirected(1, [(0, 0)])) # [0, 0]
print(find_cycle_undirected(3, [(0, 1), (1, 2)])) # NoneWhy `v` Is Always an Ancestor Here
Undirected DFS has no cross edges. Every non-tree edge joins a vertex to one of its ancestors. The function also returns at the first non-tree edge it sees, and that edge is always seen from the descendant's side. Suppose ancestor a and descendant b share a non-tree edge. If b were already visited when a reached that edge, then b would have scanned the same edge earlier and returned a cycle at that point. So at the moment of detection, v is on the current path and the parent walk ends at v.
The edge cases from the earlier chapter also produce sensible output:
| Input | Output | Why |
|---|---|---|
| Two parallel edges `(0, 1)` | `[0, 1, 0]` | The second edge has a different index, so it is not skipped. |
| Self-loop `(0, 0)` | `[0, 0]` | `v == u` is visited and the edge is not the parent edge. |
| Disconnected forest | `None` | The outer loop starts a DFS in every component. |
Returning Edges Instead of Vertices
In a multigraph a vertex list can be ambiguous. [0, 1, 0] does not say which of several 0–1 edges form the cycle. If callers need to know, store parent_edge_id[v] = eid next to parent[v], and during the walk collect parent_edge_id[x] for each x plus the closing edge eid. The extra cost is the same O(k).
Verifying a Reported Cycle
A reconstruction bug can produce a list that looks like a cycle but isn't. A short checker catches that in tests:
def is_valid_directed_cycle(adj, cycle):
if cycle is None or len(cycle) < 2 or cycle[0] != cycle[-1]:
return False
inner = cycle[:-1]
if len(set(inner)) != len(inner):
return False # repeated vertex: not a simple cycle
return all(cycle[i + 1] in adj[cycle[i]] for i in range(len(cycle) - 1))
if __name__ == "__main__":
adj = [[1], [2], [3], [1]]
print(is_valid_directed_cycle(adj, [1, 2, 3, 1])) # True
print(is_valid_directed_cycle(adj, [0, 1, 2, 3, 1])) # False (includes the tail)The cycles these functions return are always simple: no vertex repeats except the first and last. A tree path cannot repeat a vertex, and the closing edge only adds the endpoint again.
Common Mistakes
- Walking to the root. This includes the tail leading into the cycle. Stop when
x == v. - Forgetting to reverse. The unreversed list follows edges backward. For undirected graphs that is still a valid cycle. For directed graphs it is not.
- Setting the parent on every edge scan. Assign
parent[v]only whenvis first discovered, or later edges will overwrite the tree path. - Recursing on huge graphs. Python's default recursion limit is about 1000, so a long path raises
RecursionError. The next chapter rewrites this search with an explicit stack.
Exercise
For the directed graph adj = [[1], [2], [0, 3], [4], [2]], with DFS starting at vertex 0 and scanning neighbors in list order, which cycle does findcycledirected return, and why isn't it the cycle through vertices 2, 3, and 4?
Show answer
It returns [0, 1, 2, 0]. DFS visits 0, then 1, then 2, and the first neighbor 2 scans is 0, which is gray. That back edge is found before DFS ever goes to 3, and the function returns at the first back edge. The cycle 2 -> 3 -> 4 -> 2 exists but is never reached.
Exercise
In findcycleundirected, what goes wrong if the check if eid == parent_edge: continue is replaced by if v == parent[u]: continue?
Show answer
Parallel edges are no longer detected. For edges [(0, 1), (0, 1)], vertex 1 skips both edges back to its parent 0, because the check compares vertices instead of edge identities, so the function returns None even though the two edges form the cycle [0, 1, 0].
Exercise
Change findcycledirected so it returns a list of edge pairs, such as [(1, 2), (2, 3), (3, 1)], instead of a vertex list. What is the smallest change?
Show answer
Keep buildcycle as written, then convert its result: given cycle = buildcycle(u, v), return list(zip(cycle, cycle[1:])). Each consecutive pair in the reversed vertex list is an edge, so zipping the list with itself shifted by one gives the edges in order.