Detect Cycle in a Directed Graph
Last Updated :
23 Jul, 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], [0, 2], [1, 2], [2, 0], [2, 3]]
Cycle: 0 → 2 → 0 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}, {0, 2}, {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 },
{ 0, 2 },
{ 1, 2 },
{ 2,
0 }, // This edge creates a cycle (0 → 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], [0, 2], [1, 2], [2, 0], [2, 3]]
# Output: True, because there is a cycle (0 → 2 → 0)
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[] { 0, 2 },
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 ], [ 0, 2 ], [ 1, 2 ], [ 2, 0 ], [ 2, 3 ] ];
console.log(isCyclic(V, edges)); // 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.
In the below article, another O(V + E) method is discussed : Detect Cycle in a direct graph using colors
[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}, {0, 2}, {1, 2}, {2, 0}, {2, 3}};
// Output: true (cycle exists)
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 }, { 0, 2 }, { 1, 2 }, { 2, 0 }, { 2, 3 }
};
// Output: true (cycle detected)
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], [0, 2], [1, 2], [2, 0], [2, 3]]
# Output: true (because there is a cycle: 0 → 2 → 0)
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[] { 0, 2 },
new int[] { 1, 2 }, new int[] { 2, 0 },
new int[] { 2, 3 } };
// Output whether the graph contains a cycle
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 ], [ 0, 2 ], [ 1, 2 ], [ 2, 0 ], [ 2, 3 ] ];
// Output: true (cycle exists: 0 → 2 → 0)
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.
Detect Cycle in a Directed graph using colors
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem