Open In App

Detect cycle in an undirected graph using BFS

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an undirected graph, how to check if there is a cycle in the graph? For example, the following graph has a cycle of 1-0-2-1. 

cycleGraph

We have discussed cycle detection for the directed graph. We have also discussed a union-find algorithm for cycle detection in undirected graphs.. The time complexity of the union-find algorithm is O(ELogV). Like directed graphs, we can use DFS to detect a cycle in an undirected graph in O(V+E) time. We have discussed DFS based solution for cycle detection in an undirected graph. 

In this article, the BFS based solution is discussed. The basic idea is to keep track of visited nodes during BFS traversal. If a node is encountered more than once during BFS, it indicates the presence of a cycle in the graph.

Here are the key steps for detecting cycles:

  • Start BFS traversal from each unvisited node in the graph.
  • While traversing, mark each visited node.
  • If a node is encountered that is already marked as visited, it implies the presence of a cycle.
  • Continue BFS traversal until all nodes are visited or a cycle is detected.

Implementation:

C++
// C++ Program to detect cycle in an undirected graph using BFS
#include <bits/stdc++.h>
using namespace std;

void addEdge(vector<int> adj[], int u, int v)
{
    adj[u].push_back(v);
    adj[v].push_back(u);
}

bool isCyclicConnected(vector<int> adj[], int s, int V, vector<bool>& visited){
    // Create a queue for BFS
    queue<int> q;

    // Enqueue the current node
    q.push(s);

    while (!q.empty()) {
        // Dequeue a vertex from queue and print it
        int v = q.front();
        q.pop();

        if (visited[v] == 1) {
            return true; // Cycle detected
        }

        visited[v] = 1; // Mark as visited

        // Visit adjacent nodes
        for (auto it : adj[v]) {
            if (visited[it] == 0) {
                q.push(it);
            }
        }
    }
    return false;
}

bool isCyclicDisconnected(vector<int> adj[], int V){
    // Mark all the vertices as not visited
    vector<bool> visited(V, false);

    for (int i = 0; i < V; i++) {
        if (!visited[i]
            && isCyclicConnected(adj, i, V, visited))
            return true;
    }
    return false;
}

// Driver program to test methods of graph class
int main(){
    int V = 4;
    vector<int> adj[V];
    addEdge(adj, 0, 1);
    addEdge(adj, 1, 2);
    addEdge(adj, 2, 0);
    addEdge(adj, 2, 3);

    if (isCyclicDisconnected(adj, V))
        cout << "Yes";
    else
        cout << "No";

    return 0;
}
// This code is contributed by Yash Agarwal(yashagarwal2852002)
Java
import java.util.*;

public class Main {
    public static void addEdge(ArrayList<Integer>[] adj, int u, int v) {
        adj[u].add(v);
        adj[v].add(u);
    }

    public static boolean isCyclicConnected(ArrayList<Integer>[] adj, int s, int V, boolean[] visited) {
        Queue<Integer> q = new LinkedList<>();
        q.add(s);

        while (!q.isEmpty()) {
            int v = q.poll();

            if (visited[v]) {
                return true; // Cycle detected
            }

            visited[v] = true; // Mark as visited

            for (int it : adj[v]) {
                if (!visited[it]) {
                    q.add(it);
                }
            }
        }
        return false;
    }

    public static boolean isCyclicDisconnected(ArrayList<Integer>[] adj, int V) {
        boolean[] visited = new boolean[V];

        for (int i = 0; i < V; i++) {
            if (!visited[i] && isCyclicConnected(adj, i, V, visited)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int V = 4;
        ArrayList<Integer>[] adj = new ArrayList[V];
        for (int i = 0; i < V; i++) {
            adj[i] = new ArrayList<>();
        }
        addEdge(adj, 0, 1);
        addEdge(adj, 1, 2);
        addEdge(adj, 2, 0);
        addEdge(adj, 2, 3);

        if (isCyclicDisconnected(adj, V))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Python3
from collections import deque

def addEdge(adj, u, v):
    adj[u].append(v)
    adj[v].append(u)

def isCyclicConnected(adj, s, V, visited):
    q = deque()
    q.append(s)

    while q:
        v = q.popleft()

        if visited[v]:
            return True  # Cycle detected

        visited[v] = True  # Mark as visited

        for it in adj[v]:
            if not visited[it]:
                q.append(it)

    return False

def isCyclicDisconnected(adj, V):
    visited = [False] * V

    for i in range(V):
        if not visited[i] and isCyclicConnected(adj, i, V, visited):
            return True

    return False

V = 4
adj = [[] for _ in range(V)]
addEdge(adj, 0, 1)
addEdge(adj, 1, 2)
addEdge(adj, 2, 0)
addEdge(adj, 2, 3)

if isCyclicDisconnected(adj, V):
    print("Yes")
else:
    print("No")
C#
using System;
using System.Collections.Generic;

class MainClass {
    public static void addEdge(List<int>[] adj, int u, int v) {
        adj[u].Add(v);
        adj[v].Add(u);
    }

    public static bool isCyclicConnected(List<int>[] adj, int s, int V, bool[] visited) {
        Queue<int> q = new Queue<int>();
        q.Enqueue(s);

        while (q.Count > 0) {
            int v = q.Dequeue();

            if (visited[v]) {
                return true; // Cycle detected
            }

            visited[v] = true; // Mark as visited

            foreach (int it in adj[v]) {
                if (!visited[it]) {
                    q.Enqueue(it);
                }
            }
        }
        return false;
    }

    public static bool isCyclicDisconnected(List<int>[] adj, int V) {
        bool[] visited = new bool[V];

        for (int i = 0; i < V; i++) {
            if (!visited[i] && isCyclicConnected(adj, i, V, visited)) {
                return true;
            }
        }
        return false;
    }

    public static void Main(string[] args) {
        int V = 4;
        List<int>[] adj = new List<int>[V];
        for (int i = 0; i < V; i++) {
            adj[i] = new List<int>();
        }
        addEdge(adj, 0, 1);
        addEdge(adj, 1, 2);
        addEdge(adj, 2, 0);
        addEdge(adj, 2, 3);

        if (isCyclicDisconnected(adj, V))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
Javascript
function addEdge(adj, u, v) {
    adj[u].push(v);
    adj[v].push(u);
}

function isCyclicConnected(adj, s, V, visited) {
    let q = [];
    q.push(s);

    while (q.length > 0) {
        let v = q.shift();

        if (visited[v]) {
            return true; // Cycle detected
        }

        visited[v] = true; // Mark as visited

        for (let it of adj[v]) {
            if (!visited[it]) {
                q.push(it);
            }
        }
    }
    return false;
}

function isCyclicDisconnected(adj, V) {
    let visited = new Array(V).fill(false);

    for (let i = 0; i < V; i++) {
        if (!visited[i] && isCyclicConnected(adj, i, V, visited)) {
            return true;
        }
    }
    return false;
}

let V = 4;
let adj = [...Array(V)].map(() => []);
addEdge(adj, 0, 1);
addEdge(adj, 1, 2);
addEdge(adj, 2, 0);
addEdge(adj, 2, 3);

if (isCyclicDisconnected(adj, V))
    console.log("Yes");
else
    console.log("No");

Output
Yes

Time Complexity: The program does a simple BFS Traversal of the graph and the graph is represented using an adjacency list. So the time complexity is O(V+E)
Space Complexity: O(V) for visited vector.



Previous Article
Next Article

Similar Reads

Detect Cycle in a Directed Graph using BFS
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains two cycles 0-&gt;1-&gt;2-&gt;3-&gt;0 and 2-&gt;4-&gt;2, so your function must return true. Recommended: Please solve it on "PRACTICE" f
11 min read
Detect cycle in an undirected graph
Given an undirected graph, The task is to check if there is a cycle in the given graph. Example: Input: N = 4, E = 4 Output: Yes Explanation: The diagram clearly shows a cycle 0 to 2 to 1 to 0 Input: N = 4, E = 3 , 0 1, 1 2, 2 3 Output: No Explanation: There is no cycle in the given graph Recommended PracticeDetect cycle in an undirected graphTry I
11 min read
What is Undirected Graph? | Undirected Graph meaning
An undirected graph is a type of graph where the edges have no specified direction assigned to the them. Characteristics of an Undirected Graph:Edges in an undirected graph are bidirectional in nature.In an undirected graph, there is no concept of a "parent" or "child" vertex as there is no direction to the edges.An undirected graph may contain loo
2 min read
Detect cycle in the graph using degrees of nodes of graph
Given a graph, the task is to detect a cycle in the graph using degrees of the nodes in the graph and print all the nodes that are involved in any of the cycles. If there is no cycle in the graph then print -1. Examples: Input: Output: 0 1 2 Approach: Recursively remove all vertices of degree 1. This can be done efficiently by storing a map of vert
11 min read
Detect cycle in Directed Graph using Topological Sort
Given a Directed Graph consisting of N vertices and M edges and a set of Edges[][], the task is to check whether the graph contains a cycle or not using Topological sort. Topological sort of directed graph is a linear ordering of its vertices such that, for every directed edge U -&gt; V from vertex U to vertex V, U comes before V in the ordering. E
9 min read
Detect a negative cycle in a Graph using Shortest Path Faster Algorithm
Given a graph G consisting of nodes valued [0, N - 1], a source S, and an array Edges[][3] of type {u, v, w} that denotes that there is a directed edge between node u and v with weight w, the task is to check if there exists a negative cycle from the given source. If found to be true, then print "Yes". Otherwise, print "No". A negative cycle is a c
11 min read
Detect Cycle in Graph using DSU
Given an undirected graph, the task is to check if the graph contains a cycle or not, using DSU. Examples: Input: The following is the graph Output: YesExplanation: There is a cycle of vertices {0, 1, 2}. Recommended PracticeDetect Cycle using DSUTry It!We already have discussed an algorithm to detect cycle in directed graph. Here Union-Find Algori
13 min read
Detect Cycle in a directed graph using colors
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. Example: Input: n = 4, e = 6 0 -&gt; 1, 0 -&gt; 2, 1 -&gt; 2, 2 -&gt; 0, 2 -&gt; 3, 3 -&gt; 3 Output: Yes Explanation: This diagram clearly shows a cycle 0 -&gt; 2 -&gt; 0. Inpu
11 min read
Shortest cycle in an undirected unweighted graph
Given an undirected unweighted graph. The task is to find the length of the shortest cycle in the given graph. If no cycle exists print -1. Examples: Input: Output: 4 Cycle 6 -&gt; 1 -&gt; 5 -&gt; 0 -&gt; 6 Input: Output: 3 Cycle 6 -&gt; 1 -&gt; 2 -&gt; 6 Prerequisites: Dijkstra Approach: For every vertex, we check if it is possible to get the shor
8 min read
Minimum labelled node to be removed from undirected Graph such that there is no cycle
Given an undirected graph of N nodes labelled from 1 to N, the task is to find the minimum labelled node that should be removed from the graph such that the resulting graph has no cycle. Note: If the initial graph has no cycle, i.e. no node needs to be removed, print -1. Examples: Input: N = 5, edges[][] = {{5, 1}, {5, 2}, {1, 2}, {2, 3}, {2, 4}} O
15+ min read