Detect Cycle in Undirected Graph (DFS)
Does an undirected graph contain a cycle? Detect it with DFS.
Open on GeeksforGeeks ↗Intuition
Identical rule to the BFS version — an already-visited neighbour that is not the parent closes a loop — but the parent travels down the recursion instead of inside a queue. Such an edge is called a back edge, and in an undirected graph a back edge and a cycle are the same thing.
Approach
Pass the parent down
dfs(v, parent): mark v, then for each neighbour u either recurse (if unvisited) or check whether u != parent.
Back edge = cycle
A visited, non-parent neighbour is an edge back into the part of the graph already on the path — the definition of a cycle here.
Why directed graphs need more
In a directed graph an edge into a finished vertex is harmless, so the parent trick fails; that variant needs the grey/black recursion-stack check instead.
Solution & live demo
Edge cases
Every visited neighbour is the parent — returns false.
u == v is visited and not the parent — correctly a cycle.
Outer loop covers every component.