Detect Cycle in Undirected Graph (BFS)
Does an undirected graph contain a cycle? Detect it with BFS.
Open on GeeksforGeeks ↗Intuition
In an undirected graph every edge can be walked back the way you came, so 'neighbour already visited' is not enough to prove a cycle — it might just be your parent. Carry the parent along in the queue: an already-visited neighbour that is not the parent means a second, independent path reached it, which closes a loop.
Approach
The parent exception
Queue (vertex, parent) pairs. When examining a neighbour that is already visited, ignore it if it is the parent — that is only the edge you arrived on.
Any other visited neighbour is a cycle
If a visited neighbour is not the parent, two distinct paths reach it, so the graph has a cycle. Return immediately.
Repeat per component
A cycle may hide in any component, so restart BFS at each unvisited vertex.
Solution & live demo
Edge cases
Never finds a non-parent visited neighbour — no cycle.
Each component is checked separately.
The second edge looks like a non-parent revisit and is correctly reported as a cycle.