Detect Cycle in Directed Graph (DFS)
Does a directed graph contain a cycle? Use DFS with three colours.
Open on GeeksforGeeks ↗Intuition
The undirected parent trick breaks here: reaching an already-visited vertex is fine if that vertex is completely finished — it just means two paths converge. What matters is whether the target is still on the current recursion stack. Three colours capture that: white (untouched), grey (on the stack), black (finished). An edge into grey is a cycle.
Approach
Why two states are not enough
With only visited/unvisited, the DAG 0→1, 0→2, 1→2 falsely reports a cycle when 0→2 finds 2 already visited. The fix is distinguishing 'finished' from 'in progress'.
Grey means on the stack
Colour a vertex grey on entry and black on exit. An edge into a grey vertex points back into the path currently being explored — a genuine cycle.
Black edges are safe
An edge into a black vertex is a shortcut into an already-completed subtree; it cannot close a loop, so it is ignored.
Solution & live demo
Edge cases
The shared vertex is black by then, so no false positive.
v is grey while its own edges are scanned — reported immediately.
Outer loop starts a DFS in each component.