Sub topic 10
Detecting Cycles
This chapter assumes you have read the earlier chapters on recursive and iterative DFS, the DFS forest, discovery and finish times, and edge classification. You should be comfortable with Python dictionaries and sets, recursion, and the difference between directed and undirected graphs.
A cycle is a path that starts and ends at the same vertex. Detecting cycles matters in many settings. A build system must reject circular dependencies. A deadlock detector looks for cycles in a "waits-for" graph. A topological sort, covered in the next chapter, only exists when the graph has no cycles. DFS answers the question in O(V + E) time. The test differs between directed and undirected graphs, and mixing up the two tests is the most common bug.
The Key Fact: Cycles Mean Back Edges
The previous chapter classified every edge DFS examines. One result is the basis for everything in this chapter:
- A directed graph has a cycle if and only if DFS finds a back edge.
- An undirected graph has a cycle if and only if DFS finds an edge to an already-visited vertex that is not the vertex it just came from.
A back edge goes from a vertex to one of its ancestors in the DFS tree. The ancestor is still "open": DFS has started it and not yet finished it. The tree path from the ancestor down to the current vertex, together with the back edge, forms a cycle.
The converse holds as well. Suppose a cycle exists, and let v be the first vertex on it that DFS discovers. Every other vertex on the cycle is reachable from v, so all of them get discovered and finished before v finishes. The cycle vertex u whose edge points to v therefore examines u → v while v is still open, and that edge is a back edge.
Directed Graphs: Three Colors
A plain visited set cannot tell an open ancestor apart from a vertex that was finished earlier. The usual fix is to give each vertex one of three colors:
| Color | Meaning | Edge to it means |
|---|---|---|
| White | Not yet discovered | Tree edge: recurse |
| Gray | Discovered, still on the recursion path | Back edge: cycle |
| Black | Finished, all descendants explored | Forward or cross edge: no cycle |
WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle(graph):
color = {node: WHITE for node in graph}
def visit(node):
color[node] = GRAY
for neighbor in graph[node]:
if color[neighbor] == GRAY:
return True # back edge: cycle found
if color[neighbor] == WHITE and visit(neighbor):
return True
color[node] = BLACK
return False
return any(color[node] == WHITE and visit(node) for node in graph)
print(has_cycle({"a": ["b"], "b": ["c"], "c": ["a"]})) # True
print(has_cycle({"a": ["b"], "b": ["c"], "c": []})) # FalseThe outer any(...) starts a fresh DFS from every white vertex. Without that loop, a cycle in a part of the graph that the first start vertex cannot reach would go unnoticed.
Why a Visited Set Is Not Enough
Take the "diamond" graph A → B, A → C, B → D, C → D. DFS visits A, B, D, and then C. When C looks at D, D has already been visited, yet the graph has no cycle. D is black at that point, so C → D is a cross edge, which is harmless. If you treat "already visited" as "cycle" in a directed graph, you get false positives on every graph where two paths meet.
Reporting the Cycle Itself
A yes or no answer is often too little. A build tool should print the loop that caused the error, such as a → b → c → a. The gray vertices always form the current recursion path, in order. If you keep that path as an explicit list, the cycle is the slice from the gray vertex you just hit to the end of the list.
WHITE, GRAY, BLACK = 0, 1, 2
def find_cycle(graph):
color = {node: WHITE for node in graph}
path = []
def visit(node):
color[node] = GRAY
path.append(node)
for neighbor in graph[node]:
if color[neighbor] == GRAY:
return path[path.index(neighbor):] + [neighbor]
if color[neighbor] == WHITE:
found = visit(neighbor)
if found:
return found
path.pop()
color[node] = BLACK
return None
for node in graph:
if color[node] == WHITE:
found = visit(node)
if found:
return found
return None
print(find_cycle({"a": ["b"], "b": ["c"], "c": ["a", "d"], "d": []})) # ['a', 'b', 'c', 'a']
print(find_cycle({"x": ["x"]})) # ['x', 'x']
print(find_cycle({"a": ["b"], "b": []})) # NoneA self-loop x → x is a cycle of length one. The code handles it without a special case because x is gray when it examines its own edge. path.index is linear, but it runs only once, when the search stops, so the total stays O(V + E).
Iterative Version
Recursion depth equals the length of the longest DFS path. A dependency chain of 10,000 vertices exceeds Python's default recursion limit of about 1,000. The iterative DFS from the earlier chapter marked vertices when they were popped, so it never knew when a vertex finished, and it could not tell gray from black. To fix that, keep an iterator over each vertex's neighbors on the stack. A vertex turns black when its iterator runs out.
WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle_iterative(graph):
color = {node: WHITE for node in graph}
for start in graph:
if color[start] != WHITE:
continue
color[start] = GRAY
stack = [(start, iter(graph[start]))]
while stack:
node, neighbors = stack[-1]
advanced = False
for neighbor in neighbors:
if color[neighbor] == GRAY:
return True
if color[neighbor] == WHITE:
color[neighbor] = GRAY
stack.append((neighbor, iter(graph[neighbor])))
advanced = True
break
if not advanced:
color[node] = BLACK
stack.pop()
return False
chain = {i: [i + 1] for i in range(20000)}
chain[20000] = [0]
print(has_cycle_iterative(chain)) # True, with no recursion limit problemThe iterator remembers where each vertex stopped scanning its neighbors. When DFS returns to a vertex, it picks up from the next neighbor and does not rescan the list, so each edge is still examined once.
Undirected Graphs: Ignore the Edge You Came In On
In an undirected adjacency list, every edge appears twice: u lists v and v lists u. When DFS moves from u to v, the vertex v sees u as an already-visited neighbor. That is the same edge seen from the other end, not a cycle. So you pass the parent along and skip it:
def has_cycle_undirected(graph):
visited = set()
def visit(node, parent):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
if visit(neighbor, node):
return True
elif neighbor != parent:
return True # visited, and not the edge we arrived by
return False
return any(node not in visited and visit(node, None) for node in graph)
triangle = {"a": ["b", "c"], "b": ["a", "c"], "c": ["a", "b"]}
path = {"a": ["b"], "b": ["a", "c"], "c": ["b"]}
print(has_cycle_undirected(triangle)) # True
print(has_cycle_undirected(path)) # FalseUndirected DFS produces no cross or forward edges, only tree edges and back edges. That is why a visited set is enough here and colors are not needed.
A quick check without DFS also works: a connected undirected graph with V vertices is acyclic exactly when it has V − 1 edges. Across a whole graph, it is acyclic when E = V − C, where C is the number of connected components. Union-find is another common alternative when edges arrive one at a time.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Using "visited" as the cycle test in a directed graph | False cycles on diamonds and shared dependencies | Use three colors and report only gray hits |
| Forgetting the parent check in an undirected graph | Every graph with an edge reports a cycle | Skip the edge you arrived by |
| Starting DFS from only one vertex | Cycles in unreachable parts are missed | Loop over all vertices and launch from each white one |
| Missing keys for sink vertices | `KeyError` on `graph[neighbor]` | Include every vertex as a key, even with an empty list |
| Never turning vertices black | Revisits make the run exponential, and colors stay wrong | Set black after the neighbor loop finishes |
| Deep recursion on long chains | `RecursionError` | Use the iterator-stack version |
Exercise
Run the three-color has_cycle on the directed graph {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}. What color is D when C examines the edge C → D, and what does the function return?
Show answer
D is black. DFS went A → B → D, D had no neighbors and finished, then B finished. When C examines D, the edge is a cross edge, not a back edge, so it is not reported. The function returns False because the graph is acyclic.
Exercise
Your undirected cycle detector is called on {"a": ["b"], "b": ["a"]} and returns True. What bug most likely causes this?
Show answer
The parent check is missing or wrong. When DFS goes from a to b, b sees a as already visited. Without skipping the parent, the code treats the reverse direction of the single edge a–b as a cycle. The correct check returns True only for a visited neighbor that is not the parent.
Exercise
Why can't you detect directed cycles with the iterative DFS that marks vertices visited when they are popped, and what change makes it work?
Show answer
That version never records when a vertex finishes, so it cannot tell a vertex on the current path (gray) apart from a finished one (black). Keep a (vertex, neighbor iterator) pair on the stack. Mark a vertex gray when it is pushed and black when its iterator is exhausted and it is popped. An edge to a gray vertex is then a back edge.