[Approach 1] Using DFS - O(V + E) Time and O(V) Space
The problem can be solved based on the following idea:
To find cycle in a directed graph we can use the Depth First Traversal (DFS) technique. It is based on the idea that there is a cycle in a graph only if there is a back edge [i.e., a node points to one of its ancestors in a DFS tree] present in the graph.
To detect a back edge, we need to keep track of the visited nodes that are in the current recursion stack [i.e., the current path that we are visiting]. Please note that all ancestors of a node are present in recursion call stack during DFS. So if there is an edge to an ancestor in DFS, then this is a back edge.
To keep track of vertices that are in recursion call stack, we use a boolean array where we use vertex number as an index. Whenever we begin recursive call for a vertex, we mark its entry as true and whenever the recursion call is about to end, we mark false.
Illustration:
Note: If the graph is disconnected then get the DFS forest and check for a cycle in individual graphs by checking back edges.
C++
#include<bits/stdc++.h>usingnamespacestd;// Utility function for DFS to detect a cycle in a directed graphboolisCyclicUtil(vector<vector<int>>&adj,intu,vector<bool>&visited,vector<bool>&recStack){// If the node is already in the recursion stack, a cycle is detectedif(recStack[u])returntrue;// If the node is already visited and not in recursion stack, no need to check againif(visited[u])returnfalse;// Mark the current node as visited and add it to the recursion stackvisited[u]=true;recStack[u]=true;// Recur for all neighborsfor(intx:adj[u]){if(isCyclicUtil(adj,x,visited,recStack))returntrue;}// Remove the node from the recursion stackrecStack[u]=false;returnfalse;}// Function to construct an adjacency list from edge listvector<vector<int>>constructadj(intV,vector<vector<int>>&edges){vector<vector<int>>adj(V);for(auto&it:edges){adj[it[0]].push_back(it[1]);// Directed edge from it[0] to it[1]}returnadj;}// Function to detect cycle in a directed graphboolisCyclic(intV,vector<vector<int>>&edges){// Construct the adjacency listvector<vector<int>>adj=constructadj(V,edges);// visited[] keeps track of visited nodes// recStack[] keeps track of nodes in the current recursion stackvector<bool>visited(V,false);vector<bool>recStack(V,false);// Check for cycles starting from every unvisited nodefor(inti=0;i<V;i++){if(!visited[i]&&isCyclicUtil(adj,i,visited,recStack))returntrue;// Cycle found}returnfalse;// No cycles detected}intmain(){intV=4;// Number of vertices// Directed edges of the graphvector<vector<int>>edges={{0,1},{0,2},{1,2},{2,0},{2,3}};// Output whether the graph contains a cyclecout<<(isCyclic(V,edges)?"true":"false")<<endl;return0;}
Java
importjava.util.*;classGfG{// Function to perform DFS and detect cycle in a// directed graphprivatestaticbooleanisCyclicUtil(List<Integer>[]adj,intu,boolean[]visited,boolean[]recStack){// If the current node is already in the recursion// stack, a cycle is detectedif(recStack[u])returntrue;// If already visited and not in recStack, it's not// part of a cycleif(visited[u])returnfalse;// Mark the current node as visited and add it to// the recursion stackvisited[u]=true;recStack[u]=true;// Recur for all adjacent verticesfor(intv:adj[u]){if(isCyclicUtil(adj,v,visited,recStack))returntrue;}// Backtrack: remove the vertex from recursion stackrecStack[u]=false;returnfalse;}// Function to construct adjacency list from edge listprivatestaticList<Integer>[]constructAdj(intV,int[][]edges){// Create an array of listsList<Integer>[]adj=newArrayList[V];for(inti=0;i<V;i++){adj[i]=newArrayList<>();}// Add edges to the adjacency list (directed)for(int[]edge:edges){adj[edge[0]].add(edge[1]);}returnadj;}// Main function to check if the directed graph contains// a cyclepublicstaticbooleanisCyclic(intV,int[][]edges){List<Integer>[]adj=constructAdj(V,edges);boolean[]visited=newboolean[V];boolean[]recStack=newboolean[V];// Perform DFS from each unvisited vertexfor(inti=0;i<V;i++){if(!visited[i]&&isCyclicUtil(adj,i,visited,recStack))returntrue;// Cycle found}returnfalse;// No cycle found}publicstaticvoidmain(String[]args){intV=4;// Number of vertices// Directed edges of the graphint[][]edges={{0,1},{0,2},{1,2},{2,0},// This edge creates a cycle (0 → 2 → 0){2,3}};// Print resultSystem.out.println(isCyclic(V,edges)?"true":"false");}}
Python
# Helper function for DFS-based cycle detectiondefisCyclicUtil(adj,u,visited,recStack):# If the node is already in the current recursion stack, a cycle is detectedifrecStack[u]:returnTrue# If the node is already visited and not part of the recursion stack, skip itifvisited[u]:returnFalse# Mark the current node as visited and add it to the recursion stackvisited[u]=TruerecStack[u]=True# Recur for all the adjacent verticesforvinadj[u]:ifisCyclicUtil(adj,v,visited,recStack):returnTrue# Remove the node from the recursion stack before returningrecStack[u]=FalsereturnFalse# Function to build adjacency list from edge listdefconstructadj(V,edges):adj=[[]for_inrange(V)]# Create a list for each vertexforu,vinedges:adj[u].append(v)# Add directed edge from u to vreturnadj# Main function to detect cycle in the directed graphdefisCyclic(V,edges):adj=constructadj(V,edges)visited=[False]*V# To track visited verticesrecStack=[False]*V# To track vertices in the current DFS path# Try DFS from each vertexforiinrange(V):ifnotvisited[i]andisCyclicUtil(adj,i,visited,recStack):returnTrue# Cycle foundreturnFalse# No cycle found# Example usageV=4# Number of verticesedges=[[0,1],[0,2],[1,2],[2,0],[2,3]]# Output: True, because there is a cycle (0 → 2 → 0)print(isCyclic(V,edges))
C#
usingSystem;usingSystem.Collections.Generic;classGfG{// Function to check if the graph has a cycle using DFSprivatestaticboolIsCyclicUtil(List<int>[]adj,intu,bool[]visited,bool[]recStack){if(recStack[u])returntrue;if(visited[u])returnfalse;visited[u]=true;recStack[u]=true;foreach(intvinadj[u]){if(IsCyclicUtil(adj,v,visited,recStack))returntrue;}recStack[u]=false;returnfalse;}// Function to construct adjacency listprivatestaticList<int>[]Constructadj(intV,int[][]edges){List<int>[]adj=newList<int>[V];for(inti=0;i<V;i++){adj[i]=newList<int>();}foreach(varedgeinedges){adj[edge[0]].Add(edge[1]);}returnadj;}// Function to check if a cycle exists in the graphpublicstaticboolisCyclic(intV,int[][]edges){List<int>[]adj=Constructadj(V,edges);bool[]visited=newbool[V];bool[]recStack=newbool[V];for(inti=0;i<V;i++){if(!visited[i]&&IsCyclicUtil(adj,i,visited,recStack))returntrue;}returnfalse;}publicstaticvoidMain(){intV=4;int[][]edges={newint[]{0,1},newint[]{0,2},newint[]{1,2},newint[]{2,0},newint[]{2,3}};Console.WriteLine(isCyclic(V,edges));}}
JavaScript
// Helper function to perform DFS and detect cyclefunctionisCyclicUtil(adj,u,visited,recStack){// If node is already in the recursion stack, cycle// detectedif(recStack[u])returntrue;// If node is already visited and not in recStack, no// need to check againif(visited[u])returnfalse;// Mark the node as visited and add it to the recursion// stackvisited[u]=true;recStack[u]=true;// Recur for all neighbors of the current nodefor(letvofadj[u]){if(isCyclicUtil(adj,v,visited,recStack))returntrue;// If any path leads to a cycle,// return true}// Backtrack: remove the node from recursion stackrecStack[u]=false;returnfalse;// No cycle found in this path}// Function to construct adjacency list from edge listfunctionconstructadj(V,edges){letadj=Array.from({length:V},()=>[]);// Create an empty list for each vertexfor(let[u,v]ofedges){adj[u].push(v);// Add directed edge from u to v}returnadj;}// Main function to detect cycle in directed graphfunctionisCyclic(V,edges){letadj=constructadj(V,edges);// Build adjacency listletvisited=newArray(V).fill(false);// Track visited nodesletrecStack=newArray(V).fill(false);// Track recursion stack// Check each vertex (for disconnected components)for(leti=0;i<V;i++){if(!visited[i]&&isCyclicUtil(adj,i,visited,recStack))returntrue;// Cycle found}returnfalse;// No cycle detected}// Example usageletV=4;letedges=[[0,1],[0,2],[1,2],[2,0],[2,3]];console.log(isCyclic(V,edges));// Output: true
Output
true
Time Complexity: O(V + E), the Time Complexity of this method is the same as the time complexity of DFS traversal which is O(V+E). Auxiliary Space: O(V), storing the visited array and recursion stack requires O(V) space.
We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.
[Approach 2] Using Topological Sorting - O(V + E) Time and O(V) Space
Here we are using Kahn's algorithm for topological sorting, if it successfully removes all vertices from the graph, it's a DAG with no cycles. If there are remaining vertices with in-degrees greater than 0, it indicates the presence of at least one cycle in the graph. Hence, if we are not able to get all the vertices in topological sorting then there must be at least one cycle.
C++
#include<bits/stdc++.h>usingnamespacestd;// Function to construct adjacency list from the given edgesvector<vector<int>>constructAdj(intV,vector<vector<int>>&edges){vector<vector<int>>adj(V);for(auto&edge:edges){adj[edge[0]].push_back(edge[1]);// Directed edge from edge[0] to edge[1]}returnadj;}// Function to check if a cycle exists in the directed graph using Kahn's Algorithm (BFS)boolisCyclic(intV,vector<vector<int>>&edges){vector<vector<int>>adj=constructAdj(V,edges);// Build the adjacency listvector<int>inDegree(V,0);// Array to store in-degree of each vertexqueue<int>q;// Queue to store nodes with in-degree 0intvisited=0;// Count of visited (processed) nodes// Step 1: Compute in-degrees of all verticesfor(intu=0;u<V;++u){for(intv:adj[u]){inDegree[v]++;}}// Add all vertices with in-degree 0 to the queuefor(intu=0;u<V;++u){if(inDegree[u]==0){q.push(u);}}// Perform BFS (Topological Sort)while(!q.empty()){intu=q.front();q.pop();visited++;// Reduce in-degree of neighborsfor(intv:adj[u]){inDegree[v]--;if(inDegree[v]==0){// Add to queue when in-degree becomes 0q.push(v);}}}// If visited nodes != total nodes, a cycle existsreturnvisited!=V;}intmain(){intV=4;// Number of verticesvector<vector<int>>edges={{0,1},{0,2},{1,2},{2,0},{2,3}};// Output: true (cycle exists)cout<<(isCyclic(V,edges)?"true":"false")<<endl;return0;}
Java
importjava.util.*;classGfG{// Function to construct an adjacency list from edge// liststaticList<Integer>[]constructadj(intV,int[][]edges){List<Integer>[]adj=newArrayList[V];// Initialize each adjacency listfor(inti=0;i<V;i++){adj[i]=newArrayList<>();}// Add directed edges to the adjacency listfor(int[]edge:edges){adj[edge[0]].add(edge[1]);// Directed edge from// edge[0] to edge[1]}returnadj;}// Function to check if the directed graph contains a// cycle using Kahn's AlgorithmstaticbooleanisCyclic(intV,int[][]edges){List<Integer>[]adj=constructadj(V,edges);// Build graphint[]inDegree=newint[V];// Array to store in-degree of// each vertexQueue<Integer>q=newLinkedList<>();// Queue for BFSintvisited=0;// Count of visited (processed) nodes// Compute in-degrees of all verticesfor(intu=0;u<V;u++){for(intv:adj[u]){inDegree[v]++;}}// Enqueue all nodes with in-degree 0for(intu=0;u<V;u++){if(inDegree[u]==0){q.offer(u);}}// Perform BFS (Topological Sort)while(!q.isEmpty()){intu=q.poll();visited++;// Reduce in-degree of all adjacent verticesfor(intv:adj[u]){inDegree[v]--;if(inDegree[v]==0){q.offer(v);}}}// If not all vertices were visited, there's a// cyclereturnvisited!=V;}publicstaticvoidmain(String[]args){intV=4;// Number of verticesint[][]edges={{0,1},{0,2},{1,2},{2,0},{2,3}};// Output: true (cycle detected)System.out.println(isCyclic(V,edges)?"true":"false");}}
Python
fromcollectionsimportdeque# Function to construct adjacency list from edge listdefconstructadj(V,edges):adj=[[]for_inrange(V)]# Initialize empty list for each vertexforu,vinedges:adj[u].append(v)# Directed edge from u to vreturnadj# Function to check for cycle using Kahn's Algorithm (BFS-based Topological Sort)defisCyclic(V,edges):adj=constructadj(V,edges)in_degree=[0]*Vqueue=deque()visited=0# Count of visited nodes# Calculate in-degree of each nodeforuinrange(V):forvinadj[u]:in_degree[v]+=1# Enqueue nodes with in-degree 0foruinrange(V):ifin_degree[u]==0:queue.append(u)# Perform BFS (Topological Sort)whilequeue:u=queue.popleft()visited+=1# Decrease in-degree of adjacent nodesforvinadj[u]:in_degree[v]-=1ifin_degree[v]==0:queue.append(v)# If visited != V, graph has a cyclereturnvisited!=V# Example usageV=4edges=[[0,1],[0,2],[1,2],[2,0],[2,3]]# Output: true (because there is a cycle: 0 → 2 → 0)print("true"ifisCyclic(V,edges)else"false")
C#
usingSystem;usingSystem.Collections.Generic;classGfG{// Function to construct an adjacency list from the// given edge liststaticList<int>[]constructadj(intV,int[][]edges){List<int>[]adj=newList<int>[V];// Initialize each list in the arrayfor(inti=0;i<V;i++){adj[i]=newList<int>();}// Populate adjacency list for directed graphforeach(varedgeinedges){adj[edge[0]].Add(edge[1]);// Add directed edge from edge[0]// to edge[1]}returnadj;}// Function to check whether the graph contains a cycle// using Kahn's AlgorithmstaticboolisCyclic(intV,int[][]edges){List<int>[]adj=constructadj(V,edges);// Build adjacency listint[]inDegree=newint[V];Queue<int>q=newQueue<int>();intvisited=0;// Calculate in-degree of each vertexfor(intu=0;u<V;u++){foreach(intvinadj[u]){inDegree[v]++;}}// Add vertices with in-degree 0 to queuefor(intu=0;u<V;u++){if(inDegree[u]==0){q.Enqueue(u);}}// Process queue using BFSwhile(q.Count>0){intu=q.Dequeue();visited++;// Count the visited node// Decrease in-degree of adjacent verticesforeach(intvinadj[u]){inDegree[v]--;if(inDegree[v]==0){q.Enqueue(v);// Add vertex to queue when// in-degree becomes 0}}}// If not all vertices were visited, there's a// cyclereturnvisited!=V;}// Main function to run the programpublicstaticvoidMain(){intV=4;// Define edges of the graph (directed)int[][]edges={newint[]{0,1},newint[]{0,2},newint[]{1,2},newint[]{2,0},newint[]{2,3}};// Output whether the graph contains a cycleConsole.WriteLine(isCyclic(V,edges)?"true":"false");}}
JavaScript
// Function to construct the adjacency list from edge listfunctionconstructadj(V,edges){// Initialize an adjacency list with V empty arraysletadj=Array.from({length:V},()=>[]);// Populate the adjacency list (directed edge u → v)for(let[u,v]ofedges){adj[u].push(v);}returnadj;}// Function to detect a cycle in a directed graph using// Kahn's AlgorithmfunctionisCyclic(V,edges){letadj=constructadj(V,edges);letinDegree=newArray(V).fill(0);letqueue=[];letvisited=0;for(letu=0;u<V;u++){for(letvofadj[u]){inDegree[v]++;}}// Enqueue all nodes with in-degree 0for(letu=0;u<V;u++){if(inDegree[u]===0){queue.push(u);}}// Process nodes with in-degree 0while(queue.length>0){letu=queue.shift();// Dequeuevisited++;// Mark node as visited// Reduce in-degree of adjacent nodesfor(letvofadj[u]){inDegree[v]--;if(inDegree[v]===0){queue.push(v);// Enqueue if in-degree becomes 0}}}// If not all nodes were visited, there's a cyclereturnvisited!==V;}// Example usageconstV=4;constedges=[[0,1],[0,2],[1,2],[2,0],[2,3]];// Output: true (cycle exists: 0 → 2 → 0)console.log(isCyclic(V,edges)?"true":"false");
Output
true
Time Complexity: O(V + E), the time complexity of this method is the same as the time complexity of BFS traversal which is O(V+E). Auxiliary Space: O(V), for creating queue and array indegree.
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.