Cycle Detection in Undirected Graphs
Cycle Detection in Undirected Graphs
Overview
Cycle detection in undirected graphs determines whether a cycle exists in the graph. A cycle occurs when we can start at a vertex, follow edges, and return to the starting vertex without traversing any edge twice.
Two Main Approaches
- DFS-based: Track visited nodes and parent to detect back edges
- Union-Find (Disjoint Set Union): Detect cycle when trying to union already-connected vertices
Approach 1: DFS Detection
Key Insight
During DFS traversal, a cycle exists if we encounter a vertex that:
- Has already been visited
- Is NOT the parent of the current vertex
If we only skip the parent, any other visited neighbor indicates a cycle.