VOOZH about

URL: https://www.geeksforgeeks.org/dsa/detect-cycle-in-an-undirected-graph-using-bfs/

⇱ Detect cycle in an undirected graph using BFS - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Detect cycle in an undirected graph using BFS

Last Updated : 11 Jul, 2025

Given an undirected graph, the task is to determine if cycle is present in it or not.

Examples:

Input: V = 5, edges[][] = [[0, 1], [0, 2], [0, 3], [1, 2], [3, 4]]

👁 Detect-Cycle-in-Undirected-Graph-2
Undirected Graph with 5 Node

Output: true
Explanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0.

Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]]

👁 Detect-Cycle-in-Undirected-Graph--1
Undirected graph with 4 Node

Output: false

Approach:

The idea is to use BFS to detect a cycle in an undirected graph. We start BFS for all components of the graph and check if a node has been visited earlier, ensuring that we do not consider the parent node of the current node while making this check. If we encounter a visited node that is not the parent, a cycle exists in the graph. Otherwise, we continue BFS by marking the node as visited and inserting it into the queue.

Step by step approach:

  1. Initialize a visited array of size n (number of nodes) to false.
  2. Iterate through all nodes from 0 to n-1. If a node is not visited, start BFS.
  3. Push the node into the queue with its parent set to -1.
  4. Perform BFS:
    • Pop a node from the queue.
    • Traverse all its adjacent nodes.
    • If an adjacent node is visited and is not the parent, return true (cycle detected).
    • Otherwise, if the adjacent node is not visited, mark it as visited and push it into the queue with the current node as its parent.
  5. If no cycle is found after checking all components, return false.

Implementation:


Output
true

Time Complexity:O(V+E), It visits each node once and processes each edge once using an adjacency list.
Space Complexity: O(V), O(V) for the queue and visited array.

We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.

Related Articles:


Comment
Article Tags: