01Cycles in directed graphs
In a directed graph, “I reached a visited vertex” is not enough to claim a cycle: that vertex may have been finished on another branch. You need all three colours. During DFS at u, look at each edge u → w:
- w white: a tree edge, recurse;
- w gray: w is still on the recursion stack, an ancestor of u, so the path w → … → u plus the edge u → w is a cycle;
- w black: w and everything below it is finished; no cycle through here.
In the course graph the DFS path 1 → 2 → 4 → 5 is gray when we meet the new edge 5 → 1 (AI → Intro). Vertex 1 is gray, so we found a cycle, and no study plan can exist. To print the cycle, keep parents and walk back from u to w.
In an undirected graph the rule is simpler: any visited neighbour other than your parent closes a cycle.