Approach: This problem can be solved using DFS of Graph and Stack to store vertices of Graph.
Create a variable x to store starting of the cycle and create a stack to store the vertices of the cycle.
DFS traverses the given graph and marks the node as visited.
For every child of this node check if the child has not visited DFS traverse the child.
Otherwise, if the child is visited and also it is not the parent of the current node then we have detected the cycle and thus the value of x becomes the child node value.
Below is the implementation of the above approach:
C++
// C++ code for the above approach:#include<bits/stdc++.h>usingnamespacestd;vector<int>vis;vector<vector<int>>adj;stack<int>s;// x will indicate the starting// point of the cycleintx;// Function to detect cycleboolcycleDetect(intnode,intparent){booldetected=false;vis[node]=1;s.push(node);for(autochild:adj[node]){if(!vis[child]){detected=cycleDetect(child,node);if(detected)break;}elseif(child!=parent){x=child;returntrue;}}if(!detected)s.pop();returndetected;}// Driver codeintmain(){// Take input for graphintn=4;vis.resize(n+1,0);adj.resize(n+1);adj[1].push_back(2);adj[1].push_back(3);adj[3].push_back(1);adj[3].push_back(2);adj[2].push_back(3);adj[2].push_back(4);adj[2].push_back(1);adj[4].push_back(2);// Cycle Detection using DFSbooldetected=false;for(inti=1;i<=n;i++){if(!vis[i])detected=cycleDetect(i,0);if(detected)break;}if(detected){cout<<"Cycle exists.\n";cout<<s.top();s.pop();while(s.top()!=x){cout<<" -> "<<s.top();s.pop();}cout<<" -> "<<s.top();}elsecout<<"Cycle does not exist.\n";return0;}
Java
// Java code for the above approach:importjava.util.*;publicclassGFG{staticint[]vis;staticArrayList<ArrayList<Integer>>adj;staticStack<Integer>s;// x will indicate the starting// point of the cyclestaticintx;// Function to detect cyclestaticbooleancycleDetect(intnode,intparent){booleandetected=false;vis[node]=1;s.push(node);for(Integerchild:adj.get(node)){if(vis[child]==0){detected=cycleDetect(child,node);if(detected)break;}elseif(child!=parent){x=child;returntrue;}}if(!detected)s.pop();returndetected;}// Driver codepublicstaticvoidmain(String[]args){// Take input for graphintn=4;vis=newint[n+1];s=newStack<>();adj=newArrayList<>();for(inti=0;i<n+1;i++){adj.add(newArrayList<>());}adj.get(1).add(2);adj.get(1).add(3);adj.get(3).add(1);adj.get(3).add(2);adj.get(2).add(3);adj.get(2).add(4);adj.get(2).add(1);adj.get(4).add(2);// Cycle Detection using DFSbooleandetected=false;for(inti=1;i<=n;i++){if(vis[i]==0)detected=cycleDetect(i,0);if(detected)break;}if(detected){System.out.println("Cycle exists.");System.out.print(s.peek());s.pop();while(s.peek()!=x){System.out.print(" -> "+s.peek());s.pop();}System.out.print(" -> "+s.peek());}elseSystem.out.println("Cycle does not exist.");}}// This code is contributed by karandeep1234
Python3
# Python3 code for the above approach:# x will indicate the starting# point of the cyclex=0n=4vis=[]s=[]# Function to detect cycledefcycleDetect(node,parent,s,adj,x):detected=Falsevis[node]=1s.append(node)child=adj[node][0]if(vis[child]==0):detected=cycleDetect(child,node,s,adj,x)elif(child!=parent):x=childreturnx,Trueif(detected==False):s.pop()returndetected# Driver code# Take input for graphforiinrange(0,n+1):vis.append(0)adj=[]foriinrange(0,n+1):a=[]adj.append(a)adj[1].append(2)adj[1].append(3)adj[3].append(1)adj[3].append(2)adj[2].append(3)adj[2].append(4)adj[2].append(1)adj[4].append(2)# Cycle Detection using DFSdetected=Falseforiinrange(1,n+1):if(vis[i]==False):x,detected=cycleDetect(i,0,s,adj,x)if(detected):break# returning ansans=""if(detected):print("Cycle exists.")ans+=str(s[len(s)-1])s.pop()while(s[len(s)-1]!=x):ans+=" -> "+str(s[len(s)-1])s.pop()ans+=" -> "+str(s[len(s)-1])print(ans)else:print("Cycle does not exist.")# This code is contributed by akashish__
C#
usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;publicclassGFG{// x will indicate the starting// point of the cyclepublicstaticintx;// Function to detect cyclepublicstaticboolcycleDetect(intnode,intparent,Stack<int>s,int[]vis,List<List<int>>adj){booldetected=false;vis[node]=1;s.Push(node);intchild=adj[node][0];if(vis[child]==0){detected=cycleDetect(child,node,s,vis,adj);}elseif(child!=parent){x=child;returntrue;}if(!detected)s.Pop();returndetected;}staticpublicvoidMain(){// Take input for graphintn=4;int[]vis=newint[n+1];Stack<int>s=newStack<int>();List<List<int>>adj=newList<List<int>>();for(inti=0;i<n+1;i++){adj.Add(newList<int>());}adj[1].Add(2);adj[1].Add(3);adj[3].Add(1);adj[3].Add(2);adj[2].Add(3);adj[2].Add(4);adj[2].Add(1);adj[4].Add(2);// Cycle Detection using DFSbooldetected=false;for(inti=1;i<=n;i++){if(vis[i]==0)detected=cycleDetect(i,0,s,vis,adj);if(detected)break;}if(detected){Console.WriteLine("Cycle exists.");Console.Write(s.Peek());s.Pop();while((int)s.Peek()!=x){Console.Write(" -> ");Console.Write(s.Peek());s.Pop();}Console.Write(" -> ");Console.Write(s.Peek());}elseConsole.WriteLine("Cycle does not exist.");}}// This code is contributed by akashish__
JavaScript
// JS code for the above approach:// x will indicate the starting// point of the cycleletx=0;// Function to detect cyclefunctioncycleDetect(node,parent,s,adj){letdetected=false;vis[node]=1;s.push(node);child=adj[node][0];if(!vis[child]){detected=cycleDetect(child,node,s,adj);}elseif(child!=parent){x=child;returntrue;}if(!detected)s.pop();returndetected;}// Driver code// Take input for graphletn=4;letvis=[];lets=[];for(leti=0;i<n+1;i++){vis.push(0);}letadj=[];for(leti=0;i<n+1;i++){leta=[];adj.push(a);}adj[1].push(2);adj[1].push(3);adj[3].push(1);adj[3].push(2);adj[2].push(3);adj[2].push(4);adj[2].push(1);adj[4].push(2);// Cycle Detection using DFSletdetected=false;for(leti=1;i<=n;i++){if(!vis[i])detected=cycleDetect(i,0,s,adj);if(detected)break;}// returning ansletans="";if(detected){console.log("Cycle Exists");ans+=s[s.length-1];s.pop();while(s[s.length-1]!=x){ans+=" -> "+s[s.length-1]s.pop();}ans+=" -> "+s[s.length-1];console.log(ans);}elseconsole.log("Cycle does not exist.");// This code is contributed by akashish__
Output
Cycle exists.
3 -> 2 -> 1
Time Complexity: O(V + E) where V is the number of vertices and E is the number of edges in the graph. Auxiliary Space: O(V) where V is the number of vertices in the graph.
Another Method: Check cycle exists or Not:-
For finding the cycle in an undirected graph we use DFS. Use dfs from every unvisited node. There is a cycle in an undirected graph only if there is a back edge present in the graph. To find the back edge to any of its ancestors keep a visited array and if there is a back edge to any visited node then there is a loop and return true.
Approach:
Follow the below steps to implement the above approach:
First iterate over all the nodes of the graph and keep vis[] array for keeping the track of the visited nodes.
Run a DFS (Depth First Search) traversal on the given subgraph connected to the current node and then pass the parent of the current node.
For every recursion set vis[root] = 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, return the result of the DFS.
Else if the adjacent node is visited
if it is not the parent of the current node
then return true.
else return false.
C++
// A C++ Program to detect// cycle in an undirected graph#include<bits/stdc++.h>usingnamespacestd;// Class for an undirected graphclassGraph{// Number of verticesintV;// Pointer to an array// containing adjacency listslist<int>*adj;boolcheckcycleUtil(intv,boolvis[],intparent);public:// ConstructorGraph(intV);// To add an edge to graphvoidaddEdge(intv,intw);// Returns true if there is a cycleboolcheckcycle();};Graph::Graph(intV){this->V=V;adj=newlist<int>[V];}voidGraph::addEdge(intv,intw){// Add w to v’s list.adj[v].push_back(w);// Add v to w’s list.adj[w].push_back(v);}// A recursive function that// uses vis[] and parent to detect// cycle in subgraph reachable// from vertex v.boolGraph::checkcycleUtil(intv,boolvis[],intparent){// Mark the current node as visvis[v]=true;// Recur for all the vertices// adjacent to this vertexlist<int>::iteratori;for(i=adj[v].begin();i!=adj[v].end();++i){// If an adjacent vertex is not vis,// then recur for that adjacentif(!vis[*i]){if(checkcycleUtil(*i,vis,v))returntrue;}// If an adjacent vertex is vis and// is not parent of current vertex,// then there exists a cycle in the graph.elseif(*i!=parent)returntrue;}returnfalse;}// Returns true if the graph contains// a cycle, else false.boolGraph::checkcycle(){// Mark all the vertices as not// vis and not part of recursion// stackbool*vis=newbool[V];for(inti=0;i<V;i++)vis[i]=false;// Call the recursive helper// function to detect cycle in different// DFS treesfor(intu=0;u<V;u++){// Don't recur for u if// it is already visif(!vis[u])if(checkcycleUtil(u,vis,-1))returntrue;}returnfalse;}// Driver program to test above functionsintmain(){Graphgraph1(5);graph1.addEdge(1,0);graph1.addEdge(0,2);graph1.addEdge(2,1);graph1.addEdge(0,3);graph1.addEdge(3,4);graph1.checkcycle()?cout<<"Graph1 contains cycle\n":cout<<"Graph1 doesn't contain cycle\n";return0;}// ksam24000
Java
// Java Code to implement above approachimportjava.util.*;publicclassGFG{// Class for an undirected graphstaticclassGraph{// Number of verticesintV;// Pointer to an array// containing adjacency listsArrayList<ArrayList<Integer>>adj;// A recursive function that// uses vis[] and parent to detect// cycle in subgraph reachable// from vertex v.privatebooleancheckcycleUtil(intv,booleanvis[],intparent){// Mark the current node as visvis[v]=true;// Recur for all the vertices// adjacent to this vertexfor(Integeri:adj.get(v)){// If an adjacent vertex is not vis,// then recur for that adjacentif(!vis[i]){if(checkcycleUtil(i,vis,v))returntrue;}// If an adjacent vertex is vis and// is not parent of current vertex,// then there exists a cycle in the graph.elseif(i!=parent)returntrue;}returnfalse;}// ConstructorGraph(intV){this.V=V;adj=newArrayList<>();for(inti=0;i<V;i++){adj.add(newArrayList<>());}}// To add an edge to graphpublicvoidaddEdge(intv,intw){// Add w to v’s list.adj.get(v).add(w);// Add v to w’s list.adj.get(w).add(v);}// Returns true if the graph contains// a cycle, else false.publicbooleancheckcycle(){// Mark all the vertices as not// vis and not part of recursion// stackboolean[]vis=newboolean[V];for(inti=0;i<V;i++)vis[i]=false;// Call the recursive helper// function to detect cycle in different// DFS treesfor(intu=0;u<V;u++){// Don't recur for u if// it is already visif(!vis[u])if(checkcycleUtil(u,vis,-1))returntrue;}returnfalse;}}// Driver program to test above functionspublicstaticvoidmain(String[]args){Graphgraph1=newGraph(5);graph1.addEdge(1,0);graph1.addEdge(0,2);graph1.addEdge(2,1);graph1.addEdge(0,3);graph1.addEdge(3,4);if(graph1.checkcycle())System.out.println("Graph1 contains cycle");elseSystem.out.println("Graph1 doesn't contain cycle");;}}// This code is contributed by karandeep1234
usingSystem;usingSystem.Collections.Generic;classGFG{// Class for an undirected graphclassGraph{// Number of verticesintV;// Pointer to an array// containing adjacency listsList<List<int>>adj;// A recursive function that// uses vis[] and parent to detect// cycle in subgraph reachable// from vertex v.privateboolcheckcycleUtil(intv,bool[]vis,intparent){// Mark the current node as visvis[v]=true;// Recur for all the vertices// adjacent to this vertexforeach(intiinadj[v]){// If an adjacent vertex is not vis,// then recur for that adjacentif(!vis[i]){if(checkcycleUtil(i,vis,v))returntrue;}// If an adjacent vertex is vis and// is not parent of current vertex,// then there exists a cycle in the graph.elseif(i!=parent)returntrue;}returnfalse;}// ConstructorpublicGraph(intV){this.V=V;adj=newList<List<int>>();for(inti=0;i<V;i++){adj.Add(newList<int>());}}// To add an edge to graphpublicvoidaddEdge(intv,intw){// Add w to v’s list.adj[v].Add(w);// Add v to w’s list.adj[w].Add(v);}// Returns true if the graph contains// a cycle, else false.publicboolcheckcycle(){// Mark all the vertices as not// vis and not part of recursion// stackbool[]vis=newbool[V];for(inti=0;i<V;i++)vis[i]=false;// Call the recursive helper// function to detect cycle in different// DFS treesfor(intu=0;u<V;u++){// Don't recur for u if// it is already visif(!vis[u])if(checkcycleUtil(u,vis,-1))returntrue;}returnfalse;}}// Driver program to test above functionspublicstaticvoidMain(string[]args){Graphgraph1=newGraph(5);graph1.addEdge(1,0);graph1.addEdge(0,2);graph1.addEdge(2,1);graph1.addEdge(0,3);graph1.addEdge(3,4);if(graph1.checkcycle())Console.WriteLine("Graph1 contains cycle");elseConsole.WriteLine("Graph1 doesn't contain cycle");}}// this code is contributed by devendrawrite
JavaScript
classGraph{// Number of verticesV;// Pointer to an array// containing adjacency listsadj;// Constructorconstructor(V){this.V=V;this.adj=newArray();for(leti=0;i<V;i++){this.adj[i]=newArray();}}// To add an edge to graphaddEdge(v,w){// Add w to v’s list.this.adj[v].push(w);// Add v to w’s list.this.adj[w].push(v);}// A recursive function that// uses vis[] and parent to detect// cycle in subgraph reachable// from vertex v.checkcycleUtil(v,vis,parent){// Mark the current node as visvis[v]=true;// Recur for all the vertices// adjacent to this vertexfor(constiofthis.adj[v]){// If an adjacent vertex is not vis,// then recur for that adjacentif(!vis[i]){if(this.checkcycleUtil(i,vis,v)){returntrue;}}// If an adjacent vertex is vis and// is not parent of current vertex,// then there exists a cycle in the graph.elseif(i!=parent){returntrue;}}returnfalse;}// Returns true if the graph contains// a cycle, else false.checkcycle(){// Mark all the vertices as not// vis and not part of recursion// stackconstvis=newArray(this.V).fill(false);for(letu=0;u<this.V;u++){// Don't recur for u if// it is already visif(!vis[u]){if(this.checkcycleUtil(u,vis,-1)){returntrue;}}}returnfalse;}}constgraph1=newGraph(5);graph1.addEdge(1,0);graph1.addEdge(0,2);graph1.addEdge(2,1);graph1.addEdge(0,3);graph1.addEdge(3,4);if(graph1.checkcycle()){console.log("Graph1 contains cycle");}else{console.log("Graph1 doesn't contain cycle");}// this code is contributed by devendrasalunke
Output:
Graph1 contains cycle
Complexity:
Time Complexity: O(V + E) where V is the number of vertices and E is the number of edges in the graph. Auxiliary Space: O(V) where V is the number of vertices in the graph.