GraphsAnimated
Cycle Detection
DFS finds a back edge to an ancestor.
Time
O(V + E)
Extra space
O(V)
Use it for
Deadlocks, dependency checks.
How it works
- Walk the graph with depth-first search, remembering the node we came from (the parent).
- If we reach a node that is already visited and is not our parent, we have found a way back to an earlier node: a cycle.
- If the search finishes without that happening, the graph has no cycle (it is a forest).
- O(V + E).
Watch it run
Loading animation…