Detect cycle in an undirected graph | Practice | GeeksforGeeks

Given an undirected graph with V vertices and E edges, check whether it contains any cycle or not. 
Example 1:
Input:   

Output: 1
Explanation: 1->2->3->4->1 is a cycle.

Example 2:
Input: 

Output: 0
Explanation: No cycle in the graph.

 
Your Task:
You don't need to read or print anything. Your task is to complete the function isCycle() which takes V denoting the number of vertices and adjacency list as input parameters and returns a boolean value denoting if the undirected graph contains any cycle or not, return 1 if a cycle is present else return 0.
NOTE: The adjacency list denotes the edges of the graph where edges[i][0] and edges[i][1] represent an edge.
 
Expected Time Complexity: O(V + E)
Expected Space Complexity: O(V)

 
Constraints:
1 ≤ V, E ≤ 105
0
annanyavijay2 days ago
public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {              boolean vis[] = new boolean[V];              for(int i = 0; i < V; i++){           if(!vis[i]){               boolean result = dfs(i, adj, vis,-1);               if(result)                   return true;           }       }       return false;   }      public boolean dfs(int v, ArrayList<ArrayList<Integer>> adj, boolean vis[], int parent){              vis[v] = true;       for(Integer next: adj.get(v)){                                    if(!vis[next]){               if(dfs(next, adj, vis, parent))                   return true;           }           else if(parent != next)                   return true;                  }       return false;   }
0
udayaashu15022 days ago
   bool bfs(int node,vector<int>adj[],vector<int>&visited,int p)  {      queue<int>q;      q.push(node);      visited[node ]=p;      while(!q.empty())      {          int temp=q.front();          q.pop();              for(auto it:adj[temp])              {                  if(visited[it]==-1)                  {                      visited[it]=temp;                      q.push(it);                  }else{                      if(it!=visited[temp])                      {                          return true;                      }                  }              }      }      return false;  }  bool isCycle(int V, vector<int> adj[]) {      // Code here      vector<int>visited(V,-1);      for(int i=0;i<V;i++)      {          if(visited[i]==-1)          {              if(bfs(i,adj,visited,-2))                  return true;          }      }      return false;  }
0
singhalyash814 days ago
// { Driver Code Starts#include <bits/stdc++.h>using namespace std;
// } Driver Code Endsclass Solution { public:   // Function to detect cycle in an undirected graph.   bool bfs(int node,vector<int>adj[],vector<int>&visited,int &V)   {       queue<int>q;       q.push(node);       while(!q.empty())       {           int temp=q.front();           q.pop();           if(visited[temp]==true)               return true;           if(visited[temp]==false)           {               visited[temp]=true;               for(auto it:adj[temp])               {                   if(visited[it]==false)                       q.push(it);               }           }       }       return false;   }   bool isCycle(int V, vector<int> adj[]) {       // Code here       vector<int>visited(V,false);       for(int i=0;i<V;i++)       {           if(visited[i]==false)           {               if(bfs(i,adj,visited,V))                   return true;           }       }       return false;   }};
// { Driver Code Starts.int main() {   int tc;   cin >> tc;   while (tc--) {       int V, E;       cin >> V >> E;       vector<int> adj[V];       for (int i = 0; i < E; i++) {           int u, v;           cin >> u >> v;           adj[u].push_back(v);           adj[v].push_back(u);       }       Solution obj;       bool ans = obj.isCycle(V, adj);       if (ans)           cout << "1\n";       else           cout << "0\n";   }   return 0;}  // } Driver Code Ends
0
thakuraditya6215 days ago
Java Solution :)
 public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
        // Code here
        boolean[] visited  =new boolean[V];
        for(int i =0; i < V ;i++){
            if(visited[i] == false){
                boolean ans = BFS(adj, visited, i);
                if(ans)
                    return true;
            }
        }
        return false;
    }
    
    public boolean BFS(ArrayList<ArrayList<Integer>> adj, boolean[] visited , int src){
        ArrayDeque<Integer> queue = new ArrayDeque<>();
        queue.add(src);
        
        while(!queue.isEmpty()){
            int rem = queue.remove();
            
            if(visited[rem] == true)
                return true;
                
            visited[rem] = true;
            
            for(int nbr : adj.get(rem)){
                if(visited[nbr] == false){
                    queue.add(nbr);
                }
            }
        }
        return false;
    }
0
rimpisaksham
This comment was deleted.
+1
kharsh8225 days ago
Java Easy Solution 
// { Driver Code Starts
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
    public static void main(String[] args) throws IOException {
        BufferedReader br =
            new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine().trim());
        while (T-- > 0) {
            String[] s = br.readLine().trim().split(" ");
            int V = Integer.parseInt(s[0]);
            int E = Integer.parseInt(s[1]);
            ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
            for (int i = 0; i < V; i++) adj.add(i, new ArrayList<Integer>());
            for (int i = 0; i < E; i++) {
                String[] S = br.readLine().trim().split(" ");
                int u = Integer.parseInt(S[0]);
                int v = Integer.parseInt(S[1]);
                adj.get(u).add(v);
                adj.get(v).add(u);
            }
            Solution obj = new Solution();
            boolean ans = obj.isCycle(V, adj);
            if (ans)
                System.out.println("1");
            else
                System.out.println("0");
        }
    }
}// } Driver Code Ends


class Solution {
    // Function to detect cycle in an undirected graph.
    public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
        
        
        for(int i =0;i<V;i++){
        if(helper(adj,i,V)==true){
            return true;
        }
        }
        
        return false;
        
    }
    
    public boolean helper( ArrayList<ArrayList<Integer>> adj,int src,int V){
         boolean [] visited=new boolean[V];
         ArrayDeque <Integer> q=new ArrayDeque();
           q.add(src);
      
    
        while(q.size()!=0){
            int a =q.remove();
            
        if(visited[a]==true){
                return true;
            }
            visited[a]=true;
           
            for(int b: adj.get(a)){
                if(visited[b]==false){
                    q.add(b);
                    
                }
                
                
            }
           
           
        }
        
        return false;
    }
}
0
pegasis6 days ago
class Solution { public:  bool cycle(int node, int parent, vector<int>& vis, vector<int> adj[]){     vis[node]=1;     for(auto it: adj[node]){         if(!vis[it]){             cycle(it,node,vis,adj);         }         else if(it != parent)return 1;     }     return 0; }    // Function to detect cycle in an undirected graph.   bool isCycle(int V, vector<int> adj[]) {       // Code here       vector<int> vis(V+1,0);       for(int i=1;i<V;++i){           if(!vis[i]){               if(cycle(i,-1,vis,adj))return true;           }       }       return 0;   }};
0
sandeep55211 week ago
C++ Solution using Union find
class dist{
 public:
   vector<int> p,c;
   dist(int n){
       p.resize(n,0);
       c.resize(n,0);
       for(int i=0;i<n;i++) p[i]=i;
   }
   int find(int i){
       int b=p[i];
       int t=i;
       while(i!=b){
           i=b;
           b=p[i];
       } if(p[t]!=b) p[t]=b;
       return b;
   }
   void Union(int a,int b){
       int pa=find(a),pb=find(b);
       if(c[pa]>c[pb]){
           p[pb]=pa;
           c[pa]++;
       }
       else{
           p[pa]=pb;
           c[pb]++;
       }
   }
};
class Solution {
 public:
   // Function to detect cycle in an undirected graph.
   bool isCycle(int V, vector<int> adj[]) {
       // Code here
       dist d(V);
       vector<int> v(V,0);
       for(int i=0;i<V;i++){
           v[i]++;
           for(auto j:adj[i]){
               if(v[j]) continue;
               int a=d.find(i),b=d.find(j);
               if(a==b) return true;
               d.Union(i,j);
           }
       }
       return false;
   }
};
0
nitish kumar 171 week ago
//why it is giving wrong answer
// { Driver Code Startsimport java.util.*;import java.lang.*;import java.io.*;class GFG {   public static void main(String[] args) throws IOException {       BufferedReader br =           new BufferedReader(new InputStreamReader(System.in));       int T = Integer.parseInt(br.readLine().trim());       while (T-- > 0) {           String[] s = br.readLine().trim().split(" ");           int V = Integer.parseInt(s[0]);           int E = Integer.parseInt(s[1]);           ArrayList<ArrayList<Integer>> adj = new ArrayList<>();           for (int i = 0; i < V; i++) adj.add(i, new ArrayList<Integer>());           for (int i = 0; i < E; i++) {               String[] S = br.readLine().trim().split(" ");               int u = Integer.parseInt(S[0]);               int v = Integer.parseInt(S[1]);               adj.get(u).add(v);               adj.get(v).add(u);           }           Solution obj = new Solution();           boolean ans = obj.isCycle(V, adj);           if (ans)               System.out.println("1");           else               System.out.println("0");       }   }}// } Driver Code Ends
class Solution {    class Pair{   int first;   int second;   public Pair(int first , int second){       this.first = first;       this.second = second;   }}
 public boolean isBFSCycle(int s, ArrayList<ArrayList<Integer>> adj,boolean[]visited){      Queue<Pair> q = new LinkedList<>();      q.add(new Pair(s,-1));    visited[s]=true;      while(!q.isEmpty()){              int node = q.peek().first;       int par = q.peek().second;       q.remove();                    for(Integer it : adj.get(node) )       {                      if(visited[it]==false)           {               q.add(new Pair(it,node));               visited[it]=true;           }           else if(it!=par)           {             return true;           }       }                 }   return false;   }   // Function to detect cycle in an undirected graph.   public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {       // Code here              boolean visited[] = new boolean[V];              Arrays.fill(visited,false);                     for(int i=0;i<V;i++)       {           if(visited[i]==false)           {               if(isBFSCycle(i,adj,visited)==true)               {                   return true;               }           }       }        return false;   }  }
+1
harshscode2 weeks ago
bool dfs(int src,int par,vector<int> adj[],vector<bool> &vis) {     vis[src]=true;          for(auto x:adj[src])     {         if(!vis[x])         {             if(dfs(x,src,adj,vis))             return true;         }         else if(x!=par)         return true;     }     return false; }   bool isCycle(int v, vector<int> adj[]) {                     vector<bool> vis(v,false);              for(int i=0;i<v;i++)       {           if(!vis[i])           {           bool f=dfs(i,-1,adj,vis);           if(f)           return true;           }       }       return false;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.