GeeksforGeeks Medium

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.
Constraints
  • 1 <= V <= 10⁵
  • 0 <= E <= 10⁵
  • 0 <= edges[i][0], edges[i][1] < V
graphbfscycle
Open on GeeksforGeeks ↗
02

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.
How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

Check every neighbour of the popped vertex

Pop (u, parent) and go through adj[u]:

  • v == parent: the edge u arrived on, so skip it;
  • v already seen: another branch got there first, so return true;
  • otherwise: mark v and push (v, u).
5

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.

04

Code in Python, C++ and Java

▶1from collections import deque
▶2 
▶3class Solution:
▶4 def isCycle(self, V, edges):
▶5 adj = [[] for _ in range(V)]
▶6 for u, v in edges:
▶7 adj[u].append(v)
▶8 adj[v].append(u)
▶9 seen = [False] * V
▶10 for s in range(V):
▶11 if seen[s]:
▶12 continue
▶13 seen[s] = True
▶14 queue = deque([(s, -1)])
▶15 while queue:
▶16 u, parent = queue.popleft()
▶17 for v in adj[u]:
▶18 if v == parent:
▶19 continue
▶20 if seen[v]:
▶21 return True
▶22 seen[v] = True
▶23 queue.append((v, u))
▶24 return False
0start12345queue (vertex, came from)0startstart a BFS at 0
queue0 (start)
Vertex 0 is not seen yet, so a BFS starts there. It goes into the queue with no parent (-1), because nothing led to it. The ring shows every vertex; tags appear as vertices are reached.
0start12345queue (vertex, came from)emptytake 0 from the queue
vertex0start of this BFS
queueempty
Pop 0. Its neighbours are 1, 5, and each one gets checked in turn. It has no parent, so no neighbour is excused.
0start1from 02345queue (vertex, came from)1from 01 is new → queue it, came from 0
neighbour1not seen before
queue1 (from 0)
Vertex 1 has not been reached by any branch, so 0 claims it: mark it seen now and queue it with 0 as its parent. Marking at this moment means any other branch that later touches 1 will notice it is taken.
0start1from 02345from 0queue (vertex, came from)1from 05from 05 is new → queue it, came from 0
neighbour5not seen before
queue1 (from 0), 5 (from 0)
Vertex 5 has not been reached by any branch, so 0 claims it: mark it seen now and queue it with 0 as its parent. Marking at this moment means any other branch that later touches 5 will notice it is taken.
0start1from 02345from 0queue (vertex, came from)5from 0take 1 from the queue
vertex1reached from 0
queue5 (from 0)
Pop 1, which 0 put in the queue. Its neighbours are 0, 2, and each one gets checked in turn. Neighbour 0 is its parent, the one neighbour that proves nothing.
0start1from 02345from 0queue (vertex, came from)5from 00 is 1's parent → skip
neighbour0the parent of 1
Vertex 0 is seen, but it is the vertex that queued 1. This is the same edge 0–1 BFS walked to get here, listed again at 1's end. Counting it would call every single edge a loop, so skip it.
0start1from 02from 1345from 0queue (vertex, came from)5from 02from 12 is new → queue it, came from 1
neighbour2not seen before
queue5 (from 0), 2 (from 1)
Vertex 2 has not been reached by any branch, so 1 claims it: mark it seen now and queue it with 1 as its parent. Marking at this moment means any other branch that later touches 2 will notice it is taken.
0start1from 02from 1345from 0queue (vertex, came from)2from 1take 5 from the queue
vertex5reached from 0
queue2 (from 1)
Pop 5, which 0 put in the queue. Its neighbours are 4, 0, and each one gets checked in turn. Neighbour 0 is its parent, the one neighbour that proves nothing.
0start1from 02from 134from 55from 0queue (vertex, came from)2from 14from 54 is new → queue it, came from 5
neighbour4not seen before
queue2 (from 1), 4 (from 5)
Vertex 4 has not been reached by any branch, so 5 claims it: mark it seen now and queue it with 5 as its parent. Marking at this moment means any other branch that later touches 4 will notice it is taken.
0start1from 02from 134from 55from 0queue (vertex, came from)2from 14from 50 is 5's parent → skip
neighbour0the parent of 5
Vertex 0 is seen, but it is the vertex that queued 5. This is the same edge 0–5 BFS walked to get here, listed again at 5's end. Counting it would call every single edge a loop, so skip it.
0start1from 02from 134from 55from 0queue (vertex, came from)4from 5take 2 from the queue
vertex2reached from 1
queue4 (from 5)
Pop 2, which 1 put in the queue. Its neighbours are 1, 3, and each one gets checked in turn. Neighbour 1 is its parent, the one neighbour that proves nothing.
0start1from 02from 134from 55from 0queue (vertex, came from)4from 51 is 2's parent → skip
neighbour1the parent of 2
Vertex 1 is seen, but it is the vertex that queued 2. This is the same edge 1–2 BFS walked to get here, listed again at 2's end. Counting it would call every single edge a loop, so skip it.
0start1from 02from 13from 24from 55from 0queue (vertex, came from)4from 53from 23 is new → queue it, came from 2
neighbour3not seen before
queue4 (from 5), 3 (from 2)
Vertex 3 has not been reached by any branch, so 2 claims it: mark it seen now and queue it with 2 as its parent. Marking at this moment means any other branch that later touches 3 will notice it is taken.
0start1from 02from 13from 24from 55from 0queue (vertex, came from)3from 2take 4 from the queue
vertex4reached from 5
queue3 (from 2)
Pop 4, which 5 put in the queue. Its neighbours are 3, 5, and each one gets checked in turn. Neighbour 5 is its parent, the one neighbour that proves nothing.
0start1from 02from 13from 24from 55from 0queue (vertex, came from)3from 23 already reached from 2 → loop
neighbour3seen, and not the parent of 4
loop4 → 5 → 0 → 1 → 2 → 3 → 4
Vertex 3 is already seen, and it is not 4's parent. So two different branches reached it: one through 2, and now one through 4. Follow both branches back to where they split at 0 and add the edge 4–3: that closes the loop 4 → 5 → 0 → 1 → 2 → 3 → 4.
0start1from 02from 13from 24from 55from 0queue (vertex, came from)3from 2answer: true
answertruethe loop is shown in red
One loop is enough, so BFS stops here without reading the rest of the queue. The red vertices and edges are the loop that was found.
05

Common pitfalls

Treating every seen neighbour as a loop

✗ Wrong
for v in adj[u]:
    if seen[v]:
        return True
✓ Right
for v in adj[u]:
    if v == parent:
        continue
    if seen[v]:
        return True

The 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

✗ Wrong
prev = -1
while queue:
    u = queue.popleft()
    for v in adj[u]:
        if v == prev:
            continue
        ...
    prev = u
✓ Right
while 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.

06

Edge cases

A self-loop, such as the edge [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.

07

Complexity

Time
O(V + E)
Space
O(V + E)
Every vertex is pushed and popped once. Every edge sits in two neighbour lists and each list is read once, so the whole scan is O(V + E). The lists hold 2E entries; seen and the queue hold at most V.
08

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.