Using Breadth First Search - O(V+E) Time and O(V) Space
BFS is useful for cycle detection in an undirected graph because it explores level by level, ensuring that each node is visited in the shortest possible way. It efficiently detects cycles using a visited array and a queue while avoiding unnecessary recursive calls, making it more memory-efficient than DFS for large graphs.
During BFS traversal, we maintain a visited array and a queue. We process nodes by popping them one by one from the queue, marking them as visited, and pushing their unvisited adjacent nodes into the queue. A cycle is detected if we encounter a node that has already been visited before being dequeued, meaning it has been reached through a different path. This approach ensures that we efficiently detect cycles while maintaining optimal performance.
Using Depth First Search - O(V+E) Time and O(V) Space
Depth First Traversal can be used to detect a cycle in an undirected Graph. If we encounter a visited vertex again, then we say, there is a cycle. But there is a catch in this algorithm, we need to make sure that we do not consider every edge as a cycle because in an undirected graph, an edge from 1 to 2 also means an edge from 2 to 1. To handle this, we keep track of the parent node (the node from which we came to the current node) in the DFS traversal and ignore the parent node from the visited condition.
Follow the below steps to implement the above approach:
Iterate over all the nodes of the graph and Keep a visited array visited[] to track the visited nodes.
If the current node is not visited, run a Depth First Traversal on the given subgraph connected to the current node and pass the parent of the current node as -1. Recursively, perform the following steps:
Set visited[root] as 1.
Iterate over all adjacent nodes of the current node in the adjacency list
If it is not visited then run DFS on that node and return true if it returns true.
Else if the adjacent node is visited and not the parent of the current node then return true.
Return false.
Illustration:
Below is the graph showing how to detect cycle in a graph using DFS:
Below is the implementation of the above approach:
C++
// A C++ Program to detect cycle in an undirected graph#include<bits/stdc++.h>usingnamespacestd;boolisCycleUtil(intv,vector<vector<int>>&adj,vector<bool>&visited,intparent){// Mark the current node as visitedvisited[v]=true;// Recur for all the vertices adjacent to this vertexfor(inti:adj[v]){// If an adjacent vertex is not visited, then recur for that adjacentif(!visited[i]){if(isCycleUtil(i,adj,visited,v))returntrue;}// If an adjacent vertex is visited and is not parent of current vertex,// then there exists a cycle in the graph.elseif(i!=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;}// Returns true if the graph contains a cycle, else false.boolisCycle(intV,vector<vector<int>>&edges){vector<vector<int>>adj=constructadj(V,edges);// Mark all the vertices as not visitedvector<bool>visited(V,false);for(intu=0;u<V;u++){if(!visited[u]){if(isCycleUtil(u,adj,visited,-1))returntrue;}}returnfalse;}intmain(){intV=5;vector<vector<int>>edges={{0,1},{0,2},{0,3},{1,2},{3,4}};if(isCycle(V,edges)){cout<<"true"<<endl;}else{cout<<"false"<<endl;}return0;}
Java
importjava.util.*;classGfG{// Helper function to check cycle using DFSstaticbooleanisCycleUtil(intv,List<Integer>[]adj,boolean[]visited,intparent){visited[v]=true;// If an adjacent vertex is not visited,// then recur for that adjacentfor(inti:adj[v]){if(!visited[i]){if(isCycleUtil(i,adj,visited,v))returntrue;}// If an adjacent vertex is visited and// is not parent of current vertex,// then there exists a cycle in the graph.elseif(i!=parent){returntrue;}}returnfalse;}staticList<Integer>[]constructadj(intV,int[][]edges){List<Integer>[]adj=newArrayList[V];for(inti=0;i<V;i++){adj[i]=newArrayList<>();}returnadj;}// Function to check if graph contains a cyclestaticbooleanisCycle(intV,int[][]edges){List<Integer>[]adj=constructadj(V,edges);for(int[]edge:edges){adj[edge[0]].add(edge[1]);adj[edge[1]].add(edge[0]);}boolean[]visited=newboolean[V];// Call the recursive helper function// to detect cycle in different DFS treesfor(intu=0;u<V;u++){if(!visited[u]){if(isCycleUtil(u,adj,visited,-1))returntrue;}}returnfalse;}publicstaticvoidmain(String[]args){intV=5;int[][]edges={{0,1},{0,2},{0,3},{1,2},{3,4}};if(isCycle(V,edges)){System.out.println("true");}else{System.out.println("false");}}}
Python
# Helper function to check cycle using DFSdefisCycleUtil(v,adj,visited,parent):visited[v]=Trueforiinadj[v]:ifnotvisited[i]:ifisCycleUtil(i,adj,visited,v):returnTrueelifi!=parent:returnTruereturnFalsedefconstructadj(V,edges):adj=[[]for_inrange(V)]# Initialize adjacency listforedgeinedges:u,v=edgeadj[u].append(v)adj[v].append(u)returnadj# Function to check if graph contains a cycledefisCycle(V,edges):adj=constructadj(V,edges)visited=[False]*Vforuinrange(V):ifnotvisited[u]:ifisCycleUtil(u,adj,visited,-1):returnTruereturnFalse# Driver Codeif__name__=="__main__":V=5edges=[(0,1),(0,2),(0,3),(1,2),(3,4)]ifisCycle(V,edges):print("true")else:print("false")
C#
usingSystem;usingSystem.Collections.Generic;classCycleDetection{// Helper function to check cycle using DFSstaticboolIsCycleUtil(intv,List<int>[]adj,bool[]visited,intparent){visited[v]=true;foreach(intiinadj[v]){if(!visited[i]){if(IsCycleUtil(i,adj,visited,v))returntrue;}elseif(i!=parent){returntrue;}}returnfalse;}staticList<int>[]constructadj(intV,int[,]edges){List<int>[]adj=newList<int>[V];for(inti=0;i<V;i++){adj[i]=newList<int>();}returnadj;}// Function to check if graph contains a cyclestaticboolIsCycle(intV,int[,]edges){List<int>[]adj=constructadj(V,edges);for(inti=0;i<edges.GetLength(0);i++){intu=edges[i,0],v=edges[i,1];adj[u].Add(v);adj[v].Add(u);}bool[]visited=newbool[V];for(intu=0;u<V;u++){if(!visited[u]){if(IsCycleUtil(u,adj,visited,-1))returntrue;}}returnfalse;}publicstaticvoidMain(){intV=5;int[,]edges={{0,1},{0,2},{0,3},{1,2},{3,4}};if(IsCycle(V,edges)){Console.WriteLine("true");}else{Console.WriteLine("false");}}}
JavaScript
// Helper function to check cycle using DFSfunctionisCycleUtil(v,adj,visited,parent){visited[v]=true;for(letiofadj[v]){if(!visited[i]){if(isCycleUtil(i,adj,visited,v)){returntrue;}}elseif(i!==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;}// Function to check if graph contains a cyclefunctionisCycle(V,edges){letadj=constructadj(V,edges);letvisited=newArray(V).fill(false);// Check each nodefor(letu=0;u<V;u++){if(!visited[u]){if(isCycleUtil(u,adj,visited,-1)){returntrue;}}}returnfalse;}// Driver CodeconstV=5;constedges=[[0,1],[0,2],[0,3],[1,2],[3,4]];if(isCycle(V,edges)){console.log("true");}else{console.log("false");}
Output
true
Time Complexity: O(V+E) because DFS visits each vertex once (O(V)) and traverses all edges once (O(E)) Auxiliary space: O(V) for the visited array and O(V) for the recursive call stack.
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.