Cycle Detection
Identifying cycles in graphs using DFS traversal and recursive stack tracking.
What is Cycle Detection?
Cycle Detection is the task of finding closed loops in graphs. In directed graphs, cycles are detected during a Depth-First Search (DFS) traversal by identifying 'back-edges'. A back-edge is an edge that points from the current vertex to an ancestor vertex that is still active in the current recursion stack.
Key Characteristics:
- Detects recursive loops in directed networks.
- Maintains recursion stack state.
- Distinguishes between back-edges, forward-edges, and cross-edges.
- Essential for deadlock detection and compiler compilation orders.
Complexity Analysis
How it Works Step-by-Step
- State Init: Maintain arrays/maps for visited (fully processed) and recursion_stack (active in current DFS path).
- Loop All Nodes: For each unvisited node, run DFS.
- Push Recursion: Mark current node as visited and add to recursion_stack.
- Evaluate Neighbors: For each neighbor v, if v is in recursion_stack, a cycle is detected.
- Recurse: If neighbor v is not visited, recursively call DFS on v. If that returns true, propagate cycle detection.
- Backtrack: Remove current node from recursion_stack and return false.
Code Implementation
Worked Trace Example
Directed graph: A->B, B->C, C->A:
1. DFS(A): mark A as visited & active. Stack = {A}.
2. Visit B: DFS(B): mark B as visited & active. Stack = {A, B}.
3. Visit C: DFS(C): mark C as visited & active. Stack = {A, B, C}.
4. From C: Neighbor A is already in the recursion stack! Cycle detected.
Result: Cycle detected (A->B->C->A).
Ready to Understand Cycle Detection Visually?
Don't just read about it. Launch our interactive, premium algorithm visualizer to step through calculations in real-time.
Launch Cycle Detection Visualizer →