Detect cycle in a directed graph | Practice | GeeksforGeeks

Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, check whether it contains any cycle or not.

Example 1:
Input:



Output: 1
Explanation: 3 -> 3 is a cycle

Example 2:
Input:


Output: 0
Explanation: no cycle in the graph

Your task:
You dont need to read input or print anything. Your task is to complete the function isCyclic() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns a boolean value denoting if the given directed graph contains a cycle or not. 

Expected Time Complexity: O(V + E)
Expected Auxiliary Space: O(V)

Constraints:
1 ≤ V, E ≤ 105
-1
deepeshupadhyay856 days ago
 JAVA Easy To UnderStand
 
public boolean isCyclic(int V, ArrayList<ArrayList<Integer>> adj)
0
sakshisingh4501 week ago
class Solution { public:   // Function to detect cycle in a directed graph.   bool checkcycle(int node, vector<int> adj[], int vis[],int dfsvis[]){       vis[node]=1;       dfsvis[node]=1;       for(auto it : adj[node]){           if(!vis[it]){               if(checkcycle(it,adj,vis,dfsvis))   return true;           }           else if(dfsvis[it]) return true;       }       dfsvis[node]=0;       return false;          }   bool isCyclic(int V, vector<int> adj[]) {       // code here       int vis[V]={0};       int dfsvis[V]={0};       for(int i=0;i<V;i++){           if(!vis[i]){               if(checkcycle(i,adj,vis,dfsvis))    return true;           }       }       return false;   }};
0
jainmuskan5652 weeks ago
when getting tle try using ‘&’ reference
   // Function to detect cycle in a directed graph.   bool solve(int i, vector<bool> &visited,vector<bool>& order,vector<int>adj[]){       visited[i]=true;       order[i]=true;       for(auto neighbor:adj[i]){           if(!visited[neighbor]){               bool cyc= solve(neighbor,visited,order,adj);               if(cyc){                   return true;               }           }           else if(order[neighbor]){                   return true;               }       }       order[i]=false;       return false;   }   bool isCyclic(int V, vector<int> adj[]) {       vector<bool> visited(V,false);       vector<bool> order(V,false);              for(int i=0;i<V;i++){           if(!visited[i]){               bool cyc= solve(i,visited,order,adj);               if(cyc){                   return true;               }           }       }       return false;   }
0
harshscode2 weeks ago
the idea is basically to maintain a visited vector and order vector when recursion call is back then and make order vector 0 if we found order vector 0 then no cycle...
 bool dfs(vector<int> adj[],vector<int> &vis,vector<int> &order,int src)   {       vis[src]=1;       order[src]=1;              for(auto x:adj[src])       {           if(!vis[x])           {               if(dfs(adj,vis,order,x))               return true;           }           else if(order[x])           return true;       }              order[src]=0;       return false;   }         bool isCyclic(int v, vector<int> adj[]) {         vector<int> vis(v,0);         vector<int> order(v,0);                  for(int i=0;i<v;i++)         {             if(!vis[i])             {                 bool f=dfs(adj,vis,order,i);                 if(f)                 return true;             }         }         return false;   }
0
singh3003662 weeks ago
	bool cycle(int i, vector<bool> &visited, vector<bool> &dfsvisited, vector<int> adj[]){
        
			visited[i] = true; 
			dfsvisited[i] = true; 

			
			for(auto x: adj[i]) { 
			    if(visited[x] == false){
				if (cycle(x, visited, dfsvisited, adj)) 
					return true; 
			    }
				else if (dfsvisited[x]==true && visited[x]==true) 
					return true; 
			} 
		dfsvisited[i] = false;   
		return false;                                                                                                            
	}
		bool isCyclic(int V, vector<int> adj[]){
		vector<bool> visited(V, false); 
		vector<bool> dfsvisited(V, false); 
		for(int i = 0; i < V; i++) {
		    if(visited[i]==false){
			    if(cycle(i, visited, dfsvisited, adj)) 
				    return true;}}
		return false;
	}
 
0
singh3003662 weeks ago
class Solution{
public:
 bool cycle(int i, vector<bool> &visited, vector<bool> &dfsvisited, vector<int> adj[]){         visited[i] = true;   dfsvisited[i] = true;
    for(auto x: adj[i]) {       if(visited[x] == false){   if (cycle(x, visited, dfsvisited, adj))     return true;       }   else if (dfsvisited[x]==true && visited[x]==true)     return true;   }  dfsvisited[i] = false;    return false;                                                                                                }
 bool isCyclic(int V, vector<int> adj[]){ vector<bool> visited(V, false);  vector<bool> dfsvisited(V, false);  for(int i = 0; i < V; i++) {     if(visited[i]==false){      if(cycle(i, visited, dfsvisited, adj))        return true;}} return false;}
{;
0
singh300366
This comment was deleted.
0
subhankar3184422 weeks ago
JAVA 2.67/6.41
 public boolean isCyclic(int V, ArrayList<ArrayList<Integer>> adj) {       // code here       boolean []vis = new boolean[V];        boolean []rStack = new boolean[V];              for(int i=0; i<V; i++){           if(!vis[i]){               if(dfs(i,vis,adj,rStack))                   return true;           }       }       return false;   }   boolean dfs(int v,boolean vis[], ArrayList<ArrayList<Integer>> adj,boolean rStack[]){       vis[v] = true;       rStack[v] = true;       for(int i : adj.get(v)){           if(!vis[i]){               if(dfs(i,vis,adj,rStack))                   return true;           }           else if(rStack[i])               return true;       }       rStack[v] = false;       return false;   }
-1
jordiamposta2 weeks ago
// C++ solution
// ------------
class Solution {
public:

    bool isCyclic(int V, vector<int> adj[]) {
        // code here
        if (!V) {
            return false;
        }

        // 1 visited, 2 excluded, 0 pending
        auto node_status = std::vector<int>(V, 0);

        std::function<bool(int)> deep_search;
        deep_search = [&deep_search, &adj, &node_status](int node) {

            if (node_status[node] == 2) return false;
            else if (node_status[node] == 1) return true;

            node_status[node] = 1;

            const auto &conn = adj[node];

            for (const auto& _c: conn){
                if (deep_search(_c)) return true;
            }

            node_status[node] = 2;
            return false;
        };

        for(int i=0; i < node_status.size(); i++)
        {
            if(node_status[i] == 0 && deep_search(i)){
                return true;
            }
        }

        return false;
    }
};
0
mohammedfaisal2 weeks ago


class Solution {
    // Function to detect cycle in a directed graph.
    public boolean isCyclic(int V, ArrayList<ArrayList<Integer>> adj) {
        // code here
        
        
        

------------------------------------
        // Easy soln without recursion stack
        int[] visited = new int[V];
        
        // Visited will have 3 states. 1->Not explored, 2->Being explored
        // 3->Explored.
        
        for(int i=0; i<V; i++) {
            if( visited[i] == 0) {
                if(dfs(adj, visited, i))
                    return true;
            }
        }
        return false;
    }
    
    public boolean dfs(ArrayList<ArrayList<Integer>> adj, int[] visited, int i) {
        
        if(visited[i] == 1)        // If node being processed, cycle found.
            return true;
        
        if(visited[i] == 2)       // Node has previously been completely explored 
            return false;
        
        visited[i] = 1;           
        for(int edge : adj.get(i)) {
            if( dfs(adj, visited, edge) )
                return true;
        }
        
        visited[i] = 2;
        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.