Sub topic 8
Directed Graphs: Three-Color DFS
This chapter assumes you know recursive depth-first search (DFS), the DFS edge types from the previous chapter (tree, back, forward, and cross edges), and the parent-tracking method for undirected graphs.
Why Parent Tracking Breaks on Directed Graphs
In an undirected graph, an edge that reaches an already visited vertex, other than through the edge you arrived by, closes a cycle. A directed graph has no such guarantee. An edge can point at a visited vertex that you can never get back from.
Take the graph 0 → 1, 0 → 2, 2 → 1. DFS from 0 visits 1 and finishes it. It then visits 2 and finds the edge 2 → 1. Vertex 1 is visited and is not 2's parent, so the undirected rule reports a cycle. There is no cycle here, because no path leads from 1 back to 2 or to 0. The edge 2 → 1 is a cross edge, and cross edges and forward edges are harmless in a directed graph.
Only a back edge proves a directed cycle. A back edge points to an ancestor that DFS has not finished yet, meaning a vertex still on the current path.
The Three Colors
To tell "still on the path" apart from "finished", each vertex gets one of three colors:
| Color | Meaning | Edge into it means |
|---|---|---|
| WHITE | Not yet discovered | Tree edge: recurse into it |
| GRAY | Discovered, DFS call still running (on the current path) | Back edge: cycle found |
| BLACK | DFS call finished, all descendants explored | Forward or cross edge: ignore |
The gray vertices always form exactly the current recursion stack. So an edge from u into a gray vertex v means v is an ancestor of u. The path v → … → u plus the edge u → v is a cycle.
The Algorithm
WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle_directed(adj):
color = [WHITE] * len(adj)
def dfs(u):
color[u] = GRAY
for v in adj[u]:
if color[v] == GRAY:
return True
if color[v] == WHITE and dfs(v):
return True
color[u] = BLACK
return False
return any(color[u] == WHITE and dfs(u) for u in range(len(adj)))
print(has_cycle_directed([[1, 2], [], [1]])) # False: 2 -> 1 is a cross edge
print(has_cycle_directed([[1], [2], [0]])) # True: 0 -> 1 -> 2 -> 0
print(has_cycle_directed([[0]])) # True: self-loopThe outer any(...) restarts DFS from every vertex that is still white, so the method covers disconnected graphs. A self-loop u → u is caught right away, because u is gray when its own edge is examined. Parallel edges cause no trouble: the second copy of an edge just sees the same color as the first.
Each vertex changes color twice and each edge is examined once, so the running time is O(V + E). Memory is O(V) for the colors and the recursion stack.
Common Mistakes
- Using two colors. If you mark vertices only as visited or not visited, black and gray look the same, and you get the false positive shown above.
- Never setting BLACK. If you forget
color[u] = BLACK, every finished vertex stays gray, and later cross edges into it get reported as cycles. - Resetting to WHITE on return. Turning a finished vertex back to white makes the search re-explore it, and the running time can grow exponentially. Black vertices must stay black.
- Starting from vertex 0 only. If you skip the outer loop, the search misses cycles in parts of the graph that vertex 0 cannot reach.
- Recursion depth. Python's default recursion limit is about 1000, so a long path raises
RecursionError. A later chapter converts this algorithm to an iterative version.
Exercise
Run hascycledirected on adj = [[1], [2], [], [1, 2]]. Starting from vertex 0, what colors do vertices 1 and 2 have when DFS reaches vertex 3, and what does the function return?
Show answer
DFS from 0 visits 1 and then 2. Vertex 2 has no outgoing edges, so it turns black, then 1 turns black, then 0 turns black. The outer loop then starts DFS at vertex 3, which is still white. Its edges 3 → 1 and 3 → 2 both point to black vertices, so they are cross edges and are ignored. The function returns False.
Exercise
Why is it safe to skip a black vertex instead of exploring it again from the current vertex?
Show answer
A black vertex has already had all of its descendants explored, and no cycle was found among them. If some path led from that black vertex back to a vertex on the current gray path, that gray vertex would have been reachable while the black vertex was being explored. So it would have been visited in that earlier search and could not still be gray now. An edge into a black vertex therefore cannot complete a cycle.