Detect Cycle in a Directed Graph
Last Updated :
05 Sep, 2025
Given the number of vertices V
and a list of directed edges, determine whether the graph contains a cycle or not.
Examples:
Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 0], [2, 3]]
Output: true
Explanation: The diagram clearly shows a cycle 0 → 2 → 0
Input: V = 4, edges[][] = [[0, 1], [0, 2], [1, 2], [2, 3]
No CycleOutput: false
Explanation: The diagram clearly shows no cycle.
[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>
using namespace std;
// Utility function for DFS to detect a cycle in a directed graph
bool isCyclicUtil(vector<vector<int>> &adj, int u, vector<bool> &visited, vector<bool> &recStack)
{
// If the node is already in the recursion stack, a cycle is detected
if (recStack[u])
return true;
// If the node is already visited and not in recursion stack, no need to check again
if (visited[u])
return false;
// Mark the current node as visited and add it to the recursion stack
visited[u] = true;
recStack[u] = true;
// Recur for all neighbors
for (int x : adj[u])
{
if (isCyclicUtil(adj, x, visited, recStack))
return true;
}
// Remove the node from the recursion stack
recStack[u] = false;
return false;
}
// Function to construct an adjacency list from edge list
vector<vector<int>> constructadj(int V, 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]
}
return adj;
}
// Function to detect cycle in a directed graph
bool isCyclic(int V, vector<vector<int>> &edges)
{
// Construct the adjacency list
vector<vector<int>> adj = constructadj(V, edges);
// visited[] keeps track of visited nodes
// recStack[] keeps track of nodes in the current recursion stack
vector<bool> visited(V, false);
vector<bool> recStack(V, false);
// Check for cycles starting from every unvisited node
for (int i = 0; i < V; i++)
{
if (!visited[i] && isCyclicUtil(adj, i, visited, recStack))
return true; // Cycle found
}
return false; // No cycles detected
}
int main()
{
int V = 4; // Number of vertices
// Directed edges of the graph
vector<vector<int>> edges = {{0, 1}, {1, 2}, {2, 0}, {2, 3}};
// Output whether the graph contains a cycle
cout << (isCyclic(V, edges) ? "true" : "false") << endl;
return 0;
}
Java
import java.util.*;
class GfG {
// Function to perform DFS and detect cycle in a
// directed graph
private static boolean isCyclicUtil(List<Integer>[] adj,
int u,
boolean[] visited,
boolean[] recStack)
{
// If the current node is already in the recursion
// stack, a cycle is detected
if (recStack[u])
return true;
// If already visited and not in recStack, it's not
// part of a cycle
if (visited[u])
return false;
// Mark the current node as visited and add it to
// the recursion stack
visited[u] = true;
recStack[u] = true;
// Recur for all adjacent vertices
for (int v : adj[u]) {
if (isCyclicUtil(adj, v, visited, recStack))
return true;
}
// Backtrack: remove the vertex from recursion stack
recStack[u] = false;
return false;
}
// Function to construct adjacency list from edge list
private static List<Integer>[] constructAdj(
int V, int[][] edges)
{
// Create an array of lists
List<Integer>[] adj = new ArrayList[V];
for (int i = 0; i < V; i++) {
adj[i] = new ArrayList<>();
}
// Add edges to the adjacency list (directed)
for (int[] edge : edges) {
adj[edge[0]].add(edge[1]);
}
return adj;
}
// Main function to check if the directed graph contains
// a cycle
public static boolean isCyclic(int V, int[][] edges)
{
List<Integer>[] adj = constructAdj(V, edges);
boolean[] visited = new boolean[V];
boolean[] recStack = new boolean[V];
// Perform DFS from each unvisited vertex
for (int i = 0; i < V; i++) {
if (!visited[i]
&& isCyclicUtil(adj, i, visited, recStack))
return true; // Cycle found
}
return false; // No cycle found
}
public static void main(String[] args)
{
int V = 4; // Number of vertices
// Directed edges of the graph
int[][] edges = {
{ 0, 1 },
{ 1, 2 },
{ 2, 0 },
{ 2, 3 }
};
// Print result
System.out.println(isCyclic(V, edges) ? "true"
: "false");
}
}
Python
# Helper function for DFS-based cycle detection
def isCyclicUtil(adj, u, visited, recStack):
# If the node is already in the current recursion stack, a cycle is detected
if recStack[u]:
return True
# If the node is already visited and not part of the recursion stack, skip it
if visited[u]:
return False
# Mark the current node as visited and add it to the recursion stack
visited[u] = True
recStack[u] = True
# Recur for all the adjacent vertices
for v in adj[u]:
if isCyclicUtil(adj, v, visited, recStack):
return True
# Remove the node from the recursion stack before returning
recStack[u] = False
return False
# Function to build adjacency list from edge list
def constructadj(V, edges):
adj = [[] for _ in range(V)] # Create a list for each vertex
for u, v in edges:
adj[u].append(v) # Add directed edge from u to v
return adj
# Main function to detect cycle in the directed graph
def isCyclic(V, edges):
adj = constructadj(V, edges)
visited = [False] * V # To track visited vertices
recStack = [False] * V # To track vertices in the current DFS path
# Try DFS from each vertex
for i in range(V):
if not visited[i] and isCyclicUtil(adj, i, visited, recStack):
return True # Cycle found
return False # No cycle found
# Example usage
V = 4 # Number of vertices
edges = [[0, 1], [1, 2], [2, 0], [2, 3]]
print(isCyclic(V, edges))
C#
using System;
using System.Collections.Generic;
class GfG {
// Function to check if the graph has a cycle using DFS
private static bool IsCyclicUtil(List<int>[] adj, int u,
bool[] visited,
bool[] recStack)
{
if (recStack[u])
return true;
if (visited[u])
return false;
visited[u] = true;
recStack[u] = true;
foreach(int v in adj[u])
{
if (IsCyclicUtil(adj, v, visited, recStack))
return true;
}
recStack[u] = false;
return false;
}
// Function to construct adjacency list
private static List<int>[] Constructadj(int V,
int[][] edges)
{
List<int>[] adj = new List<int>[ V ];
for (int i = 0; i < V; i++) {
adj[i] = new List<int>();
}
foreach(var edge in edges)
{
adj[edge[0]].Add(edge[1]);
}
return adj;
}
// Function to check if a cycle exists in the graph
public static bool isCyclic(int V, int[][] edges)
{
List<int>[] adj = Constructadj(V, edges);
bool[] visited = new bool[V];
bool[] recStack = new bool[V];
for (int i = 0; i < V; i++) {
if (!visited[i]
&& IsCyclicUtil(adj, i, visited, recStack))
return true;
}
return false;
}
public static void Main()
{
int V = 4;
int[][] edges
= { new int[] { 0, 1 },
new int[] { 1, 2 }, new int[] { 2, 0 },
new int[] { 2, 3 } };
Console.WriteLine(isCyclic(V, edges));
}
}
JavaScript
// Helper function to perform DFS and detect cycle
function isCyclicUtil(adj, u, visited, recStack)
{
// If node is already in the recursion stack, cycle
// detected
if (recStack[u])
return true;
// If node is already visited and not in recStack, no
// need to check again
if (visited[u])
return false;
// Mark the node as visited and add it to the recursion
// stack
visited[u] = true;
recStack[u] = true;
// Recur for all neighbors of the current node
for (let v of adj[u]) {
if (isCyclicUtil(adj, v, visited, recStack))
return true; // If any path leads to a cycle,
// return true
}
// Backtrack: remove the node from recursion stack
recStack[u] = false;
return false; // No cycle found in this path
}
// Function to construct adjacency list from edge list
function constructadj(V, edges)
{
let adj = Array.from(
{length : V},
() => []); // Create an empty list for each vertex
for (let [u, v] of edges) {
adj[u].push(v); // Add directed edge from u to v
}
return adj;
}
// Main function to detect cycle in directed graph
function isCyclic(V, edges)
{
let adj
= constructadj(V, edges); // Build adjacency list
let visited
= new Array(V).fill(false); // Track visited nodes
let recStack
= new Array(V).fill(false); // Track recursion stack
// Check each vertex (for disconnected components)
for (let i = 0; i < V; i++) {
if (!visited[i]
&& isCyclicUtil(adj, i, visited, recStack))
return true; // Cycle found
}
return false; // No cycle detected
}
// Example usage
let V = 4;
let edges =
[[0, 1], [1, 2], [2, 0], [2, 3]];
console.log(isCyclic(V, edges));
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>
using namespace std;
// Function to construct adjacency list from the given edges
vector<vector<int>> constructAdj(int V, 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]
}
return adj;
}
// Function to check if a cycle exists in the directed graph using Kahn's Algorithm (BFS)
bool isCyclic(int V, vector<vector<int>> &edges)
{
vector<vector<int>> adj = constructAdj(V, edges);
// Build the adjacency list
vector<int> inDegree(V, 0); // Array to store in-degree of each vertex
queue<int> q; // Queue to store nodes with in-degree 0
int visited = 0; // Count of visited (processed) nodes
// Step 1: Compute in-degrees of all vertices
for (int u = 0; u < V; ++u)
{
for (int v : adj[u])
{
inDegree[v]++;
}
}
// Add all vertices with in-degree 0 to the queue
for (int u = 0; u < V; ++u)
{
if (inDegree[u] == 0)
{
q.push(u);
}
}
// Perform BFS (Topological Sort)
while (!q.empty())
{
int u = q.front();
q.pop();
visited++;
// Reduce in-degree of neighbors
for (int v : adj[u])
{
inDegree[v]--;
if (inDegree[v] == 0)
{
// Add to queue when in-degree becomes 0
q.push(v);
}
}
}
// If visited nodes != total nodes, a cycle exists
return visited != V;
}
int main()
{
int V = 4; // Number of vertices
vector<vector<int>> edges = {{0, 1}, {1, 2}, {2, 0}, {2, 3}};
cout << (isCyclic(V, edges) ? "true" : "false") << endl;
return 0;
}
Java
import java.util.*;
class GfG {
// Function to construct an adjacency list from edge
// list
static List<Integer>[] constructadj(int V,
int[][] edges)
{
List<Integer>[] adj = new ArrayList[V];
// Initialize each adjacency list
for (int i = 0; i < V; i++) {
adj[i] = new ArrayList<>();
}
// Add directed edges to the adjacency list
for (int[] edge : edges) {
adj[edge[0]].add(edge[1]); // Directed edge from
// edge[0] to edge[1]
}
return adj;
}
// Function to check if the directed graph contains a
// cycle using Kahn's Algorithm
static boolean isCyclic(int V, int[][] edges)
{
List<Integer>[] adj
= constructadj(V, edges); // Build graph
int[] inDegree
= new int[V]; // Array to store in-degree of
// each vertex
Queue<Integer> q
= new LinkedList<>(); // Queue for BFS
int visited
= 0; // Count of visited (processed) nodes
// Compute in-degrees of all vertices
for (int u = 0; u < V; u++) {
for (int v : adj[u]) {
inDegree[v]++;
}
}
// Enqueue all nodes with in-degree 0
for (int u = 0; u < V; u++) {
if (inDegree[u] == 0) {
q.offer(u);
}
}
// Perform BFS (Topological Sort)
while (!q.isEmpty()) {
int u = q.poll();
visited++;
// Reduce in-degree of all adjacent vertices
for (int v : adj[u]) {
inDegree[v]--;
if (inDegree[v] == 0) {
q.offer(v);
}
}
}
// If not all vertices were visited, there's a
// cycle
return visited != V;
}
public static void main(String[] args)
{
int V = 4; // Number of vertices
int[][] edges = {
{ 0, 1 }, { 1, 2 }, { 2, 0 }, { 2, 3 }
};
System.out.println(isCyclic(V, edges) ? "true"
: "false");
}
}
Python
from collections import deque
# Function to construct adjacency list from edge list
def constructadj(V, edges):
adj = [[] for _ in range(V)] # Initialize empty list for each vertex
for u, v in edges:
adj[u].append(v) # Directed edge from u to v
return adj
# Function to check for cycle using Kahn's Algorithm (BFS-based Topological Sort)
def isCyclic(V, edges):
adj = constructadj(V, edges)
in_degree = [0] * V
queue = deque()
visited = 0 # Count of visited nodes
# Calculate in-degree of each node
for u in range(V):
for v in adj[u]:
in_degree[v] += 1
# Enqueue nodes with in-degree 0
for u in range(V):
if in_degree[u] == 0:
queue.append(u)
# Perform BFS (Topological Sort)
while queue:
u = queue.popleft()
visited += 1
# Decrease in-degree of adjacent nodes
for v in adj[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)
# If visited != V, graph has a cycle
return visited != V
# Example usage
V = 4
edges = [[0, 1], [1, 2], [2, 0], [2, 3]]
print("true" if isCyclic(V, edges) else "false")
C#
using System;
using System.Collections.Generic;
class GfG {
// Function to construct an adjacency list from the
// given edge list
static List<int>[] constructadj(int V, int[][] edges)
{
List<int>[] adj = new List<int>[ V ];
// Initialize each list in the array
for (int i = 0; i < V; i++) {
adj[i] = new List<int>();
}
// Populate adjacency list for directed graph
foreach(var edge in edges)
{
adj[edge[0]].Add(
edge[1]); // Add directed edge from edge[0]
// to edge[1]
}
return adj;
}
// Function to check whether the graph contains a cycle
// using Kahn's Algorithm
static bool isCyclic(int V, int[][] edges)
{
List<int>[] adj = constructadj(
V, edges); // Build adjacency list
int[] inDegree = new int[V];
Queue<int> q = new Queue<int>();
int visited = 0;
// Calculate in-degree of each vertex
for (int u = 0; u < V; u++) {
foreach(int v in adj[u]) { inDegree[v]++; }
}
// Add vertices with in-degree 0 to queue
for (int u = 0; u < V; u++) {
if (inDegree[u] == 0) {
q.Enqueue(u);
}
}
// Process queue using BFS
while (q.Count > 0) {
int u = q.Dequeue();
visited++; // Count the visited node
// Decrease in-degree of adjacent vertices
foreach(int v in adj[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
// cycle
return visited != V;
}
// Main function to run the program
public static void Main()
{
int V = 4;
// Define edges of the graph (directed)
int[][] edges
= { new int[] { 0, 1 },
new int[] { 1, 2 }, new int[] { 2, 0 },
new int[] { 2, 3 } };
Console.WriteLine(isCyclic(V, edges) ? "true"
: "false");
}
}
JavaScript
// Function to construct the adjacency list from edge list
function constructadj(V, edges)
{
// Initialize an adjacency list with V empty arrays
let adj = Array.from({length : V}, () => []);
// Populate the adjacency list (directed edge u → v)
for (let [u, v] of edges) {
adj[u].push(v);
}
return adj;
}
// Function to detect a cycle in a directed graph using
// Kahn's Algorithm
function isCyclic(V, edges)
{
let adj = constructadj(V, edges);
let inDegree = new Array(V).fill(0);
let queue = [];
let visited = 0;
for (let u = 0; u < V; u++) {
for (let v of adj[u]) {
inDegree[v]++;
}
}
// Enqueue all nodes with in-degree 0
for (let u = 0; u < V; u++) {
if (inDegree[u] === 0) {
queue.push(u);
}
}
// Process nodes with in-degree 0
while (queue.length > 0) {
let u = queue.shift(); // Dequeue
visited++; // Mark node as visited
// Reduce in-degree of adjacent nodes
for (let v of adj[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 cycle
return visited !== V;
}
// Example usage
const V = 4;
const edges =
[ [ 0, 1 ], [ 1, 2 ], [ 2, 0 ], [ 2, 3 ] ];
console.log(isCyclic(V, edges) ? "true" : "false");
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.
In the below article, another O(V + E) method is discussed -
Detect Cycle in a direct graph using colors
Detect Cycle in a Directed graph using colors
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem