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:
Initialize a visited array of size n (number of nodes) to false.
Iterate through all nodes from 0 to n-1. If a node is not visited, start BFS.
Push the node into the queue with its parent set to -1.
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.
If no cycle is found after checking all components, return false.
Implementation:
C++
#include<bits/stdc++.h>usingnamespacestd;// Function to perform BFS from node startboolbfs(intstart,vector<vector<int>>&adj,vector<bool>&visited){queue<pair<int,int>>q;q.push({start,-1});visited[start]=true;while(!q.empty()){intnode=q.front().first;intparent=q.front().second;q.pop();for(intneighbor:adj[node]){if(!visited[neighbor]){visited[neighbor]=true;q.push({neighbor,node});}elseif(neighbor!=parent){returntrue;}}}returnfalse;}vector<vector<int>>constructadj(intV,vector<vector<int>>&edges){vector<vector<int>>adj(V);for(autoit:edges){adj[it[0]].push_back(it[1]);adj[it[1]].push_back(it[0]);}returnadj;}boolisCycle(intV,vector<vector<int>>&edges){vector<vector<int>>adj=constructadj(V,edges);vector<bool>visited(V,false);for(inti=0;i<V;i++){if(!visited[i]){if(bfs(i,adj,visited)){returntrue;}}}// If no cycle is foundreturnfalse;}intmain(){vector<vector<int>>edges={{0,1},{0,2},{0,3},{1,2},{3,4}};intV=5;isCycle(V,edges)?cout<<"true":cout<<"false";return0;}
Java
importjava.util.*;publicclassCycleDetection{// Function to perform BFS from a start nodestaticbooleanbfs(intstart,List<Integer>[]adj,boolean[]visited){Queue<int[]>q=newLinkedList<>();q.offer(newint[]{start,-1});visited[start]=true;while(!q.isEmpty()){int[]front=q.poll();intnode=front[0];intparent=front[1];for(intneighbor:adj[node]){if(!visited[neighbor]){visited[neighbor]=true;q.offer(newint[]{neighbor,node});}// If visited and not the parent, cycle// existselseif(neighbor!=parent){returntrue;}}}returnfalse;}staticList<Integer>[]constructadj(intV,int[][]edges){List<Integer>[]adj=newArrayList[V];for(inti=0;i<V;i++){adj[i]=newArrayList<>();}for(int[]edge:edges){intu=edge[0],v=edge[1];adj[u].add(v);adj[v].add(u);}returnadj;}staticbooleanisCycle(intV,int[][]edges){// Create adjacency listList<Integer>[]adj=constructadj(V,edges);boolean[]visited=newboolean[V];for(inti=0;i<V;i++){if(!visited[i]){if(bfs(i,adj,visited)){returntrue;}}}returnfalse;}publicstaticvoidmain(String[]args){int[][]edges={{0,1},{0,2},{0,3},{1,2},{3,4}};intV=5;System.out.println(isCycle(V,edges)?"true":"false");}}
Python
fromcollectionsimportdequedefbfs(start,adj,visited):queue=deque([(start,-1)])visited[start]=Truewhilequeue:node,parent=queue.popleft()forneighborinadj[node]:ifnotvisited[neighbor]:visited[neighbor]=Truequeue.append((neighbor,node))elifneighbor!=parent:returnTruereturnFalsedefconstructadj(V,edges):adj=[[]for_inrange(V)]# Initialize adjacency listforedgeinedges:u,v=edgeadj[u].append(v)adj[v].append(u)returnadjdefiscycle(V,edges):adj=constructadj(V,edges)visited=[False]*Vforiinrange(V):ifnotvisited[i]:ifbfs(i,adj,visited):returnTruereturnFalse# Test the functionedges=[[0,1],[0,2],[0,3],[1,2],[3,4]]V=5print("true"ifiscycle(V,edges)else"false")
C#
usingSystem;usingSystem.Collections.Generic;classCycleDetection{// Function to perform BFS from a start nodestaticboolBfs(intstart,List<int>[]adj,bool[]visited){Queue<(int,int)>q=newQueue<(int,int)>();q.Enqueue((start,-1));visited[start]=true;while(q.Count>0){var(node,parent)=q.Dequeue();foreach(intneighborinadj[node]){if(!visited[neighbor]){visited[neighbor]=true;q.Enqueue((neighbor,node));}// If visited and not the parent, cycle existselseif(neighbor!=parent){returntrue;}}}returnfalse;}// Function to construct the adjacency liststaticList<int>[]constructadj(intV,int[][]edges){List<int>[]adj=newList<int>[V];// Initialize each list in the adjacency listfor(inti=0;i<V;i++){adj[i]=newList<int>();}foreach(varedgeinedges){adj[edge[0]].Add(edge[1]);adj[edge[1]].Add(edge[0]);}returnadj;}staticboolIsCycle(intV,int[][]edges){// Create adjacency listList<int>[]adj=constructadj(V,edges);bool[]visited=newbool[V];for(inti=0;i<V;i++){if(!visited[i]){if(Bfs(i,adj,visited)){returntrue;}}}returnfalse;}staticvoidMain(){int[][]edges=newint[][]{newint[]{0,1},newint[]{0,2},newint[]{0,3},newint[]{1,2},newint[]{3,4}};intV=5;Console.WriteLine(IsCycle(V,edges)?"true":"false");}}
JavaScript
functionbfs(start,adj,visited){letqueue=[[start,-1]];visited[start]=true;while(queue.length>0){let[node,parent]=queue.shift();for(letneighborofadj[node]){if(!visited[neighbor]){visited[neighbor]=true;queue.push([neighbor,node]);}elseif(neighbor!==parent){returntrue;}}}returnfalse;}functionconstructadj(V,edges){letadj=Array.from({length:V},()=>[]);// Build the adjacency listfor(letedgeofedges){let[u,v]=edge;adj[u].push(v);adj[v].push(u);}returnadj;}functionisCycle(V,edges){letadj=constructadj(V,edges);letvisited=Array(V).fill(false);for(leti=0;i<V;i++){if(!visited[i]){if(bfs(i,adj,visited)){returntrue;}}}returnfalse;}// Test the functionletedges=[[0,1],[0,2],[0,3],[1,2],[3,4]];letV=5;console.log(isCycle(V,edges)?"true":"false");
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.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.