Detect Cycle in Undirected Graph (BFS)
Detect Cycle in Undirected Graph is a GFG problem (Medium). You are given V vertices, numbered 0 to V - 1, and a list edges in which each [u, v] is a two-way connection. Return true if you can leave some vertex and come back to it without walking any edge twice, and false if you cannot.
- The graph can be split into several pieces that do not touch, and the loop may be in any piece.
- 1 <= V <= 10⁵
- 0 <= E <= 10⁵
- 0 <= edges[i][0], edges[i][1] < V
Intuition
BFS spreads out from a start vertex in rings. Every vertex it reaches gets exactly one parent: the vertex that first put it in the queue. These parent links form a tree, and a tree never contains a loop.
So any loop must use at least one edge that is not a parent link. BFS looks at every edge from both of its ends, and when the neighbour it is looking at has already been reached, there are two cases:
- It is the parent: this is the parent link itself, seen from the child's end. Skip it.
- It is any other vertex: two different branches have reached the same vertex. The two tree paths back to where the branches split, plus this edge, make a loop.
Reach for this check whenever an undirected graph must be a tree or a forest: a network that should have no redundant links, or a set of parent-child records that must not repeat. Pick BFS over DFS when the graph might be one very long path.
Approach
Before reading on: run BFS on the single edge 0–1 with only a seen array. What does vertex 1 find when it looks at its neighbours? Then run it on the square 0–1–2–3–0 and find the exact check where two branches meet.
Build the neighbour lists
For each [u, v], add v to adj[u] and u to adj[v]. The connection works in both directions, so each end has to list the other.
Queue each vertex with its parent
Push pairs (vertex, parent). A start vertex gets parent -1, which matches no real vertex. BFS has no call stack to remember where a vertex came from, so the pair carries that fact through the queue.
Mark a vertex as seen when you queue it
Set seen[v] = True at the moment v is pushed, not when it is popped. Then seen means "some branch has already claimed this vertex", and a second branch touching it is caught at once.
Check every neighbour of the popped vertex
Pop (u, parent) and go through adj[u]:
v == parent: the edgeuarrived on, so skip it;valready seen: another branch got there first, so returntrue;- otherwise: mark
vand push(v, u).
Start a new BFS at every unseen vertex
Loop s over all vertices and begin a BFS from each s that is still unseen. One BFS only reaches its own piece of the graph. If every BFS empties its queue without a hit, return false.
Code in Python, C++ and Java
Common pitfalls
Treating every seen neighbour as a loop
for v in adj[u]:
if seen[v]:
return Truefor v in adj[u]:
if v == parent:
continue
if seen[v]:
return TrueThe edge 0–1 is stored in both lists. When 1 is popped, it finds 0 in its list, and 0 is already seen. So V = 2, edges = [[0, 1]] returns true, although one edge is not a loop.
Using the previously popped vertex as the parent
prev = -1
while queue:
u = queue.popleft()
for v in adj[u]:
if v == prev:
continue
...
prev = uwhile queue:
u, parent = queue.popleft()
for v in adj[u]:
if v == parent:
continue
...BFS takes turns between branches, so the vertex popped just before u is often not the one that queued u. In the tree [[0, 1], [0, 2]], vertex 2 is popped right after 1. It sees 0, which is seen and is not 1, and reports a loop that does not exist.
Edge cases
[2, 2]Vertex 2 appears in its own list. When 2 is popped, it finds 2 already seen, and 2 is not its own parent, so the answer is true. That is correct: an edge from a vertex to itself is a loop of length one.
Complexity
seen and the queue hold at most V.Detect Cycle in Undirected Graph (BFS) FAQ
Should I use BFS or DFS?
Both run in O(V + E) and both rely on the parent test. BFS needs no recursion, so a path of 10⁵ vertices is safe in Python without raising the recursion limit. DFS takes fewer lines. If edges arrive one at a time, Union-Find is the better fit.
Does BFS find the shortest cycle?
Not by itself. It stops at the first seen neighbour that is not a parent, which proves a loop exists, but which loop it finds depends on where the BFS started. The length of the shortest cycle needs a separate BFS from every vertex, O(V · (V + E)) in total.
How does the directed version differ?
In a directed graph two arrows can point into the same vertex without forming a loop, so "reached twice" proves nothing. The directed version uses Kahn's algorithm instead: repeatedly remove vertices with no incoming arrows, and if some vertices are never removed, they sit on a cycle.