Sub topic 8
Directed Graphs: Three-Color DFS
This chapter assumes you know Python functions, lists, and recursion. It also assumes you can read an adjacency list where adj[u] lists the vertices that u points to. You should know the undirected parent-tracking method from the earlier chapter and the tree, back, forward, and cross edge types from "Classifying DFS Edges."
The goal is a method that answers one question for a directed graph: is there a path that follows edges in their direction and returns to where it started? The answer is three-color depth-first search (DFS). It runs in O(V + E) time and reports a cycle exactly when DFS finds a back edge.
Why Parent Tracking Breaks on Directed Graphs
In an undirected graph, DFS reports a cycle when it reaches an already visited vertex through any edge other than the one it arrived on. That rule depends on symmetry. In an undirected graph, a visited vertex is always connected to the current vertex by some other path, so one extra edge closes a loop.
Directed graphs lack that symmetry, and the rule fails in two ways.
The first failure is a false positive. Take the "diamond" graph with edges 0→1, 0→2, 1→3, 2→3. DFS goes 0, 1, 3, then backs up and explores 2. From 2 it sees 3, which is already visited and is not 2's parent. The undirected rule reports a cycle, but none exists. Two paths lead to vertex 3, and neither leads back out of it.
The second failure is a false negative. Take the graph with edges 0→1 and 1→0. Directed, this is a real cycle of length 2. If you skip "the vertex I came from," DFS at vertex 1 ignores the edge 1→0 because 0 is its parent, and it misses the cycle. Skipping by edge ID would avoid this, but the false positive from the diamond would remain.
The underlying problem is that "visited" mixes two different situations:
- The vertex is on the current DFS path, which means it is an ancestor of the current vertex. An edge to it closes a directed loop.
- The vertex was fully explored earlier. An edge to it only means two paths meet, which is harmless.
Three-color DFS gives these situations separate labels.
The Three Colors
Each vertex is in one of three states:
| Color | Meaning | When it is set |
|---|---|---|
| WHITE | Not yet discovered | Initially, for every vertex |
| GRAY | Discovered, still on the recursion stack | On entering `dfs(u)` |
| BLACK | Finished: every vertex reachable from it has been explored | When `dfs(u)` returns |
At any moment, the GRAY vertices form exactly the path from the current DFS root to the current vertex. An edge u→v where v is GRAY therefore points back to an ancestor, which makes it a back edge. Following the tree path from v down to u and then taking u→v gives a directed cycle.
When DFS at u examines an edge u→v, the color of v decides what happens:
- WHITE: v is new, so recurse into it. This is a tree edge.
- GRAY: v is an ancestor still in progress, so this is a back edge and a cycle exists.
- BLACK: v is finished. This is a forward or cross edge, and it cannot close a cycle.
The Implementation
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)))
if __name__ == "__main__":
diamond = [[1, 2], [3], [3], []] # 0->1, 0->2, 1->3, 2->3
triangle = [[1], [2], [0]] # 0->1->2->0
two_cycle = [[1], [0]] # 0->1->0
self_loop = [[0]] # 0->0
split = [[1], [], [3], [4], [2]] # cycle only in 2->3->4->2
print(has_cycle_directed(diamond)) # False
print(has_cycle_directed(triangle)) # True
print(has_cycle_directed(two_cycle)) # True
print(has_cycle_directed(self_loop)) # True
print(has_cycle_directed(split)) # TrueSome details in this code are easy to get wrong:
- The outer
any(...)starts a DFS from every vertex that is still WHITE. Without it, a cycle in a part of the graph that vertex 0 cannot reach would be missed. Thesplitexample tests this case. - The
anyshort-circuits, so the function stops at the first cycle found. color[u] = BLACKcomes after the loop. Setting it earlier would hide ancestors that are still in progress.- When the function returns
Trueearly, some vertices stay GRAY. That is fine for a yes/no answer. If you reusecolorafterward, reset it first.
Tracing the Algorithm
Here is the trace on the graph 0→1, 1→2, 2→0, 0→3. The order of events is what matters.
| Step | Action | Colors (0, 1, 2, 3) | Result |
|---|---|---|---|
| 1 | Enter dfs(0) | G, W, W, W | |
| 2 | Edge 0→1, 1 is WHITE, enter dfs(1) | G, G, W, W | tree edge |
| 3 | Edge 1→2, 2 is WHITE, enter dfs(2) | G, G, G, W | tree edge |
| 4 | Edge 2→0, 0 is GRAY | G, G, G, W | back edge, return True |
Vertex 3 is never visited because the answer is already known. Now compare the diamond. Vertex 3 turns BLACK during the branch through 1. Later, edge 2→3 finds 3 BLACK and ignores it, which is correct.
Why It Is Correct
There are two directions to argue.
If a GRAY vertex is found, a cycle exists. GRAY vertices are exactly the ancestors of the current vertex u on the recursion stack. If v is GRAY, a tree path v ⇝ u exists, and the edge u→v completes the loop. A self-loop u→u is the special case where v = u, which is GRAY at that moment.
If a cycle exists, a GRAY vertex will be found. Let v be the first vertex of the cycle that DFS discovers. When v turns GRAY, every other vertex on the cycle is still WHITE, and a path of WHITE vertices leads from v around the cycle to its predecessor u. By the white-path theorem, DFS discovers every vertex on that path before v finishes, so u becomes a descendant of v. When DFS examines u→v, v is still GRAY, and the cycle is reported.
This also explains why an edge to a BLACK vertex is safe to ignore. A BLACK vertex w has finished, so everything reachable from w has already been explored. If w could reach the current vertex, that vertex would have been discovered inside w's DFS and finished before w, so it could not still be GRAY now.
Complexity
Each vertex goes from WHITE to GRAY to BLACK once, and each edge is examined once, when its source vertex is GRAY. Time is O(V + E). Extra memory is O(V) for colors plus the recursion stack, which can reach depth V on a long chain.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| One boolean `visited` array | Diamonds and other shared descendants reported as cycles | Separate GRAY (on path) from BLACK (finished) |
| Never setting BLACK | Same false positives, because finished vertices look like ancestors | Set BLACK after the neighbor loop |
| Resetting to WHITE on return | Correct answers, but exponential time on graphs with many shared subpaths | Leave finished vertices BLACK |
| Only calling `dfs(0)` | Misses cycles in unreachable parts | Loop over all WHITE start vertices |
| Skipping the parent vertex | Misses 2-cycles such as u→v→u | Do not skip parents in directed graphs |
| Treating the input as undirected | Adding both directions makes every edge a 2-cycle | Store each directed edge once, as `adj[u].append(v)` |
Edge Cases
- Self-loop u→u: detected immediately, because u is GRAY while its own edge list is scanned.
- Parallel edges u→v twice: harmless. The second copy finds v GRAY only if v is an ancestor, which would be a real cycle anyway, or BLACK otherwise.
- Empty graph or isolated vertices:
anyover no cycles returnsFalse. - Vertices labeled with strings: replace the color list with a dict keyed by vertex, and iterate over the dict's keys in the outer loop.
Exercise
Run the two-color version (a single visited flag, reporting a cycle whenever the target is already visited) on adj = [[1, 2], [2], []]. What does it report, and what does three-color DFS report? Explain the difference.
Show answer
The two-color version reports a cycle. DFS visits 0, then 1, then 2. Back at 0, the edge 0→2 hits a visited vertex. Three-color DFS reports no cycle, because vertex 2 is BLACK when 0→2 is examined, so the edge is a forward edge. The graph is acyclic: there is no path from 2 back to 0 or 1.
Exercise
In hascycledirected, suppose you move color[u] = BLACK to just before the for loop. Give a small graph where the result becomes wrong.
Show answer
adj = [[1], [0]]. dfs(0) marks 0 BLACK at once, then recurses into 1, which also turns BLACK. The edge 1→0 sees BLACK instead of GRAY, so the function returns False even though 0→1→0 is a cycle. No vertex is ever GRAY while its edges are examined, so no back edge can be detected.
Exercise
A graph has a cycle 3→4→5→3 and also edges 0→1→2 with no edges between the two groups. Why must the outer loop iterate over all vertices, and in what state are vertices 0, 1, 2 when the cycle is found?
Show answer
DFS from 0 reaches only 0, 1, 2 and finishes them all as BLACK without seeing a back edge. The cycle is reachable only from 3, 4, or 5, so the outer loop must start a new DFS at vertex 3. When the back edge 5→3 is found, vertices 0, 1, 2 are BLACK and vertices 3, 4, 5 are GRAY.