VOOZH about

URL: https://www.geeksforgeeks.org/dsa/detect-cycle-undirected-graph/

⇱ Detect cycle in an undirected graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Detect cycle in an undirected graph

Last Updated : 4 Nov, 2025

Given an adjacency list adj[][] representing an undirected graph, determine whether the graph contains a cycle/loop or not.
A cycle is a path that starts and ends at the same vertex without repeating any edge.

Examples:

Input: adj[][]= [[1, 2], [0, 2], [0, 1, 3], [2]]

👁 file

Output: true
Explanation: There is a cycle 0 → 2 → 1 → 0

Input: adj[][] = [[1], [0, 2], [1, 3], [2]]

👁 file

Output: false
Explanation: There is no cycle in the given graph.

[Approach 1] Using Depth First Search - O(V+E) Time and O(V) Space

The idea is to use Depth First Search (DFS). When we start a DFS from a node, we visit all its connected neighbors one by one. If during this traversal, we reach a node that has already been visited before, it indicates that there might be a cycle, since we’ve come back to a previously explored vertex.
However, there’s one important catch.
In an undirected graph, every edge is bidirectional. That means, if there’s an edge from u → v, then there’s also an edge from v → u.
So, while performing DFS, from u, we go to v. From v, we again see u as one of its neighbors. Since u is already visited, it might look like a cycle — but it’s not.

To avoid this issue, we keep track of the parent node — the node from which we reached the current node in DFS. When we move from u to v, we mark u as the parent of v. Now, while checking the neighbors of v, If a neighbor is not visited, we continue DFS for that node.If a neighbor is already visited and not equal to the parent, it means there’s another path that leads back to this node — and hence, a cycle exists.


Output
true

[Approach 2] Using Breadth First Search - O(V+E) Time and O(V) Space

The idea is quite similar to DFS-based cycle detection, but here we use Breadth First Search (BFS) instead of recursion. BFS explores the graph level by level, ensuring that each node is visited in the shortest possible way. It also helps avoid deep recursion calls, making it more memory-efficient for large graphs.

In BFS, we also maintain a visited array to mark nodes that have been explored and a parent tracker to remember from which node we reached the current one.
If during traversal we encounter a node that is already visited and is not the parent of the current node, it means we’ve found a cycle in the graph.


Related Articles:

Comment