Sub topic 10
Detecting Cycles
This chapter assumes you know recursive DFS, visited sets, and the edge classes from the previous chapter: tree, back, forward, and cross edges. The key fact you need is that a graph has a cycle exactly when DFS finds a back edge. A back edge points from a vertex to one of its ancestors in the DFS tree. How you recognize a back edge depends on whether the graph is directed or undirected.
Directed Graphs: Three Colors
A visited set alone cannot detect cycles in a directed graph. If DFS reaches a visited vertex, that vertex could be an ancestor on the current path, which means a cycle. It could also be a vertex in a branch that is already finished, which is a forward or cross edge and means no cycle. To tell these cases apart, you give each vertex one of three colors:
| Color | Meaning | Edge to it means |
|---|---|---|
| WHITE | Not yet discovered | Tree edge, so recurse |
| GRAY | Discovered and still on the recursion stack | Back edge, so there is a cycle |
| BLACK | Finished, with all descendants explored | Forward or cross edge, so 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 gray vertices are exactly the vertices on the current recursion path. An edge into one of them closes a loop back to that path. The outer any(...) loop restarts DFS from every white vertex, so the function also finds cycles in parts of the graph that the first start vertex cannot reach.
Undirected Graphs: Ignore the Parent
In an undirected graph, every edge u–v appears in both adjacency lists. When DFS moves from u to v, it sees u again in v's list. That edge is the tree edge you just used, so it is not a cycle. Forward and cross edges cannot occur in an undirected DFS, so any other edge to a visited vertex is a back edge. A visited set plus the parent vertex is therefore enough.
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 came in on
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)) # FalseCommon Errors
- Using the undirected check on a directed graph. Reaching a visited vertex is not enough evidence of a cycle in a directed graph. You need the GRAY versus BLACK distinction.
- Forgetting to mark BLACK. If a vertex stays GRAY after it finishes, later edges into it look like back edges, and the function reports cycles that do not exist.
- Starting from only one vertex. A cycle in a part of the graph that the start vertex cannot reach is missed. Always loop over all vertices.
- Parallel edges. If the undirected graph stores two separate edges between
uandv, the parent check skips both of them, so the 2-cycle goes undetected. In that case, track the edge ID you arrived on instead of the parent vertex. - Recursion depth. Python's default recursion limit of about 1000 is easy to exceed on long paths. For large inputs, use the explicit-stack version and keep the colors in a dictionary.
Exercise
Run the undirected check (visited set plus parent) on the directed graph {"a": ["b", "c"], "b": ["c"], "c": []}. What does it report, and what does three-color DFS report instead?
Show answer
The undirected check reports a cycle. DFS goes a → b → c, then returns to a and finds c already visited, and c is not a's parent. This answer is wrong because the graph has no cycle. Three-color DFS sees that c is BLACK (finished) when a examines it, so it classifies a → c as a forward edge and correctly returns False.
Exercise
Why can reaching a BLACK vertex never mean a cycle in a directed graph?
Show answer
A BLACK vertex has finished, so all of its descendants have been fully explored. If it could reach the current GRAY vertex, DFS would have found that path while exploring the BLACK vertex, and the current vertex would not still be unexplored at that point. So no path leads from the BLACK vertex back to the current path.