Detect Cycle in a Directed Graph
Last Updated :
14 Feb, 2025
Given the root of a Directed graph , The task is to check whether the graph contains a cycle or not.
Examples:
Input: V = 4, E = 6

Output: Yes
Explanation: The diagram clearly shows a cycle 0 -> 2 -> 0
Input: V = 4, E = 4

Output: No
Explanation: The diagram clearly shows no cycle.
[Expected 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.
Note: If the graph is disconnected then get the DFS forest and check for a cycle in individual graphs by checking back edges.
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:
Below is the graph showing how to detect cycle in a graph using DFS:
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
// Utility function to detect cycle in a directed graph
bool isCyclicUtil(vector<vector<int>> &adj, int u,
vector<bool> &visited, vector<bool> &recStack)
{
// If already present in the recursion call
// stack, then there is a cycle
if (recStack[u] == true)
return true;
// Mark the current node as visited
// and part of recursion stack
visited[u] = true;
recStack[u] = true;
// Recur for all the vertices adjacent
// to this vertex
for (int x : adj[u])
{
if (!visited[x] && isCyclicUtil(adj, x, visited, recStack))
return true;
else if (recStack[x])
return true;
}
// Remove the vertex from recursion stack
recStack[u] = false;
return false;
}
// Function to detect cycle in a directed graph
bool isCyclic(vector<vector<int>> &adj)
{
int V = adj.size();
vector<bool> visited(V, false);
vector<bool> recStack(V, false);
// Call the recursive helper function to
// detect cycle in different DFS trees
for (int i = 0; i < V; i++)
{
if (!visited[i] && isCyclicUtil(adj, i, visited, recStack))
return true;
}
return false;
}
// Driver function
int main()
{
int V = 4;
vector<vector<int>> adj(V);
// Adding edges to the graph
adj[0].push_back(1);
adj[0].push_back(2);
adj[1].push_back(2);
adj[2].push_back(0);
adj[2].push_back(3);
adj[3].push_back(3);
// Function call
if (isCyclic(adj))
cout << "Contains Cycle" << endl;
else
cout << "No Cycle" << endl;
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
class GfG {
// Utility function to detect cycle in a directed graph
private static boolean isCyclicUtil(List<List<Integer>> adj,
int src,
boolean[] visited,
boolean[] recStack) {
// If already present in the recursion call
// stack, then there is a cycle
if (recStack[src] == true)
return true;
recStack[src] = true;
visited[src] = true;
for (int next : adj.get(src)) {
if (!visited[next] &&
isCyclicUtil(adj, next, visited, recStack))
return true;
else if (recStack[next])
return true;
}
recStack[src] = false;
return false;
}
// Function to detect cycle in a directed graph
public static boolean isCyclic(List<List<Integer>> adj) {
int V = adj.size();
boolean[] visited = new boolean[V];
boolean[] recStack = new boolean[V];
// Check each unvisited node to detect cycles
for (int i = 0; i < V; i++) {
if (!visited[i] && isCyclicUtil(adj, i, visited, recStack))
return true;
}
return false;
}
// Driver function
public static void main(String[] args) {
int V = 4;
List<List<Integer>> adj = new ArrayList<>();
// Initialize adjacency list
for (int i = 0; i < V; i++)
adj.add(new ArrayList<>());
// Adding edges to the graph
adj.get(0).add(1);
adj.get(0).add(2);
adj.get(1).add(2);
adj.get(2).add(0);
adj.get(2).add(3);
adj.get(3).add(3);
// Function call to check for cycle
if (isCyclic(adj))
System.out.println("Contains cycle");
else
System.out.println("No Cycle");
}
}
Python
# Utility function to detect cycle in a directed graph
def is_cyclic_util(adj, u, visited, rec_stack):
# If already present in the recursion call
# stack, then there is a cycle
if rec_stack[u]:
return True
# Mark the current node as visited
# and part of recursion stack
visited[u] = True
rec_stack[u] = True
# Recur for all the vertices adjacent
# to this vertex
for x in adj[u]:
if not visited[x] and is_cyclic_util(adj, x, visited, rec_stack):
return True
elif rec_stack[x]:
return True
# Remove the vertex from recursion stack
rec_stack[u] = False
return False
# Function to detect cycle in a directed graph
def is_cyclic(adj):
V = len(adj)
visited = [False] * V
rec_stack = [False] * V
# Call the recursive helper function to
# detect cycle in different DFS trees
for i in range(V):
if not visited[i] and is_cyclic_util(adj, i, visited, rec_stack):
return True
return False
V = 4
adj = [[] for _ in range(V)]
# Adding edges to the graph
adj[0].append(1)
adj[0].append(2)
adj[1].append(2)
adj[2].append(0)
adj[2].append(3)
adj[3].append(3)
# Function call
if is_cyclic(adj):
print("Contains Cycle")
else:
print("No Cycle")
C#
using System;
using System.Collections.Generic;
class GfG {
// Utility function to detect cycle in a directed graph
private static bool IsCyclicUtil(List<List<int>> adj,
int src, bool[] visited, bool[] recStack) {
// If already present in the recursion call
// stack, then there is a cycle
if (recStack[src])
return true;
recStack[src] = true;
visited[src] = true;
foreach (int next in adj[src]) {
if (!visited[next] && IsCyclicUtil(adj, next, visited, recStack))
return true;
else if (recStack[next])
return true;
}
recStack[src] = false;
return false;
}
// Function to detect cycle in a directed graph
public static bool IsCyclic(List<List<int>> adj) {
int V = adj.Count;
bool[] visited = new bool[V];
bool[] recStack = new bool[V];
// Check each unvisited node to detect cycles
for (int i = 0; i < V; i++) {
if (!visited[i] && IsCyclicUtil(adj, i, visited, recStack))
return true;
}
return false;
}
// Driver function
public static void Main(string[] args) {
int V = 4;
List<List<int>> adj = new List<List<int>>();
// Initialize adjacency list
for (int i = 0; i < V; i++)
adj.Add(new List<int>());
// Adding edges to the graph
adj[0].Add(1);
adj[0].Add(2);
adj[1].Add(2);
adj[2].Add(0);
adj[2].Add(3);
adj[3].Add(3);
// Function call to check for cycle
if (IsCyclic(adj))
Console.WriteLine("Contains cycle");
else
Console.WriteLine("No Cycle");
}
}
JavaScript
// Utility function to detect cycle in a directed graph
function isCyclicUtil(adj, u, visited, recStack) {
// If already present in the recursion call
// stack, then there is a cycle
if (recStack[u]) {
return true;
}
// Mark the current node as visited
// and part of recursion stack
visited[u] = true;
recStack[u] = true;
// Recur for all the vertices adjacent
// to this vertex
for (let x of adj[u]) {
if (!visited[x] && isCyclicUtil(adj, x, visited, recStack)) {
return true;
} else if (recStack[x]) {
return true;
}
}
// Remove the vertex from recursion stack
recStack[u] = false;
return false;
}
// Function to detect cycle in a directed graph
function isCyclic(adj) {
const V = adj.length;
const visited = new Array(V).fill(false);
const recStack = new Array(V).fill(false);
// Call the recursive helper function to
// detect cycle in different DFS trees
for (let i = 0; i < V; i++) {
if (!visited[i] && isCyclicUtil(adj, i, visited, recStack)) {
return true;
}
}
return false;
}
const V = 4;
const adj = Array.from({ length: V }, () => []);
// Adding edges to the graph
adj[0].push(1);
adj[0].push(2);
adj[1].push(2);
adj[2].push(0);
adj[2].push(3);
adj[3].push(3);
if (isCyclic(adj)) {
console.log("Contains Cycle");
} else {
console.log("No Cycle");
}
OutputGraph contains cycle
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). To store the visited and recursion stack O(V) space is needed.
In the below article, another O(V + E) method is discussed :
Detect Cycle in a direct graph using colors
[Expected Approach -1] 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.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// Function to add an edge to the adjacency list
void addEdge(vector<vector<int>>& adj, int u, int v) {
adj[u].push_back(v);
}
// Function to detect cycle in a directed graph
bool isCyclic(vector<vector<int>>& adj) {
int V = adj.size();
// stores in-degree of each vertex
vector<int> inDegree(V, 0);
// queue to store vertices with 0 in-degree
queue<int> q;
int visited = 0; // count of visited vertices
// Calculate in-degree of each vertex
for (int u = 0; u < V; u++) {
for (auto v : adj[u]) {
inDegree[v]++;
}
}
// Enqueue vertices with 0 in-degree
for (int u = 0; u < V; u++) {
if (inDegree[u] == 0) {
q.push(u);
}
}
// BFS traversal
while (!q.empty()) {
int u = q.front();
q.pop();
visited++;
// Reduce in-degree of adjacent vertices
for (auto v : adj[u]) {
inDegree[v]--;
// If in-degree becomes 0, enqueue it
if (inDegree[v] == 0) {
q.push(v);
}
}
}
// If not all vertices are visited, cycle
return visited != V;
}
// Driver function
int main() {
int V = 6;
vector<vector<int>> adj(V);
// Adding edges to the graph
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 3);
addEdge(adj, 4, 1);
addEdge(adj, 4, 5);
addEdge(adj, 5, 3);
// Function call to check for cycles
if (isCyclic(adj)) {
cout << "Contains cycle" << endl;
} else {
cout << "No Cycle" << endl;
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class GraphCycleDetector {
// Function to add an edge to the adjacency list
public static void addEdge(List<List<Integer>> adj,
int u, int v) {
adj.get(u).add(v);
}
// Function to detect cycle in a directed graph
public static boolean isCyclic(List<List<Integer>> adj) {
int V = adj.size();
// Stores in-degree of each vertex
int[] inDegree = new int[V];
// Queue to store vertices with 0 in-degree
Queue<Integer> q = new LinkedList<>();
int visited = 0; // Count of visited vertices
// Calculate in-degree of each vertex
for (int u = 0; u < V; u++) {
for (int v : adj.get(u)) {
inDegree[v]++;
}
}
// Enqueue vertices with 0 in-degree
for (int u = 0; u < V; u++) {
if (inDegree[u] == 0) {
q.offer(u);
}
}
// BFS traversal
while (!q.isEmpty()) {
int u = q.poll();
visited++;
// Reduce in-degree of adjacent vertices
for (int v : adj.get(u)) {
inDegree[v]--;
// If in-degree becomes 0, enqueue it
if (inDegree[v] == 0) {
q.offer(v);
}
}
}
// If not all vertices are visited, cycle
return visited != V;
}
// Driver function
public static void main(String[] args) {
int V = 6;
List<List<Integer>> adj = new ArrayList<>();
// Initialize adjacency list
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
// Adding edges to the graph
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 3);
addEdge(adj, 4, 1);
addEdge(adj, 4, 5);
addEdge(adj, 5, 3);
// Function call to check for cycles
if (isCyclic(adj)) {
System.out.println("Contains cycle");
} else {
System.out.println("No Cycle");
}
}
}
Python
from collections import deque
# Function to add an edge to the adjacency list
def add_edge(adj, u, v):
adj[u].append(v)
# Function to detect cycle in a directed graph
def is_cyclic(adj):
V = len(adj)
# Stores in-degree of each vertex
in_degree = [0] * V
# Queue to store vertices with 0 in-degree
q = deque()
visited = 0 # Count of visited vertices
# Calculate in-degree of each vertex
for u in range(V):
for v in adj[u]:
in_degree[v] += 1
# Enqueue vertices with 0 in-degree
for u in range(V):
if in_degree[u] == 0:
q.append(u)
# BFS traversal
while q:
u = q.popleft()
visited += 1
# Reduce in-degree of adjacent vertices
for v in adj[u]:
in_degree[v] -= 1
# If in-degree becomes 0, enqueue it
if in_degree[v] == 0:
q.append(v)
# If not all vertices are visited, cycle
return visited != V
# Driver function
if __name__ == "__main__":
V = 6
adj = [[] for _ in range(V)]
# Adding edges to the graph
add_edge(adj, 0, 1)
add_edge(adj, 0, 2)
add_edge(adj, 1, 3)
add_edge(adj, 4, 1)
add_edge(adj, 4, 5)
add_edge(adj, 5, 3)
# Function call to check for cycles
if is_cyclic(adj):
print("Contains cycle")
else:
print("No Cycle")
C#
// Import necessary namespaces
using System;
using System.Collections.Generic;
public class GraphCycleDetector {
// Function to add an edge to the adjacency list
public static void AddEdge(List<List<int>> adj, int u, int v) {
adj[u].Add(v);
}
// Function to detect cycle in a directed graph
public static bool IsCyclic(List<List<int>> adj) {
int V = adj.Count;
// Stores in-degree of each vertex
int[] inDegree = new int[V];
// Queue to store vertices with 0 in-degree
Queue<int> q = new Queue<int>();
int visited = 0; // Count of visited vertices
// Calculate in-degree of each vertex
for (int u = 0; u < V; u++) {
foreach (int v in adj[u]) {
inDegree[v]++;
}
}
// Enqueue vertices with 0 in-degree
for (int u = 0; u < V; u++) {
if (inDegree[u] == 0) {
q.Enqueue(u);
}
}
// BFS traversal
while (q.Count > 0) {
int u = q.Dequeue();
visited++;
// Reduce in-degree of adjacent vertices
foreach (int v in adj[u]) {
inDegree[v]--;
// If in-degree becomes 0, enqueue it
if (inDegree[v] == 0) {
q.Enqueue(v);
}
}
}
// If not all vertices are visited, cycle
return visited != V;
}
// Driver function
public static void Main(string[] args) {
int V = 6;
List<List<int>> adj = new List<List<int>>();
// Initialize adjacency list
for (int i = 0; i < V; i++) {
adj.Add(new List<int>());
}
// Adding edges to the graph
AddEdge(adj, 0, 1);
AddEdge(adj, 0, 2);
AddEdge(adj, 1, 3);
AddEdge(adj, 4, 1);
AddEdge(adj, 4, 5);
AddEdge(adj, 5, 3);
// Function call to check for cycles
if (IsCyclic(adj)) {
Console.WriteLine("Contains cycle");
} else {
Console.WriteLine("No Cycle");
}
}
}
JavaScript
// Function to add an edge to the adjacency list
function addEdge(adj, u, v) {
adj[u].push(v);
}
// Function to detect cycle in a directed graph
function isCyclic(adj) {
let V = adj.length
// Stores in-degree of each vertex
const inDegree = Array(V).fill(0);
// Queue to store vertices with 0 in-degree
const queue = [];
let visited = 0; // Count of visited vertices
// Calculate in-degree of each vertex
for (let u = 0; u < V; u++) {
for (const v of adj[u]) {
inDegree[v]++;
}
}
// Enqueue vertices with 0 in-degree
for (let u = 0; u < V; u++) {
if (inDegree[u] === 0) {
queue.push(u);
}
}
// BFS traversal
while (queue.length > 0) {
const u = queue.shift();
visited++;
// Reduce in-degree of adjacent vertices
for (const v of adj[u]) {
inDegree[v]--;
// If in-degree becomes 0, enqueue it
if (inDegree[v] === 0) {
queue.push(v);
}
}
}
// If not all vertices are visited, cycle
return visited !== V;
}
// Driver function
const V = 6;
const adj = Array.from({ length: V }, () => []);
// Adding edges to the graph
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 3);
addEdge(adj, 4, 1);
addEdge(adj, 4, 5);
addEdge(adj, 5, 3);
// Function call to check for cycles
if (isCyclic(adj)) {
console.log("Contains cycle");
} else {
console.log("No Cycle");
}
OutputGraph does not contain cycle.
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)
Similar Reads
Graph Algorithms
Graph algorithms are methods used to manipulate and analyze graphs, solving various range of problems like finding the shortest path, cycles detection. If you are looking for difficulty-wise list of problems, please refer to Graph Data Structure. BasicsGraph and its representationsBFS and DFS Breadt
3 min read
Introduction to Graph Data Structure
Graph Data Structure is a non-linear data structure consisting of vertices and edges. It is useful in fields such as social network analysis, recommendation systems, and computer networks. In the field of sports data science, graph data structure can be used to analyze and understand the dynamics of
15+ min read
Graph and its representations
A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is den
12 min read
Types of Graphs with Examples
A graph is a mathematical structure that represents relationships between objects by connecting a set of points. It is used to establish a pairwise relationship between elements in a given set. graphs are widely used in discrete mathematics, computer science, and network theory to represent relation
9 min read
Basic Properties of a Graph
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. The basic properties of a graph include: Vertices (nodes): The points where edges meet in a graph are kn
4 min read
Applications, Advantages and Disadvantages of Graph
Graph is a non-linear data structure that contains nodes (vertices) and edges. A graph is a collection of set of vertices and edges (formed by connecting two vertices). A graph is defined as G = {V, E} where V is the set of vertices and E is the set of edges. Graphs can be used to model a wide varie
7 min read
Transpose graph
Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Giv
9 min read
Difference Between Graph and Tree
Graphs and trees are two fundamental data structures used in computer science to represent relationships between objects. While they share some similarities, they also have distinct differences that make them suitable for different applications. What is Graph?A graph data structure is a collection o
2 min read
BFS and DFS on Graph
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Traversal (BFS) starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list containing t
15+ min read
Depth First Search or DFS for a Graph
In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
13 min read
Applications, Advantages and Disadvantages of Depth First Search (DFS)
Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
4 min read
Applications, Advantages and Disadvantages of Breadth First Search (BFS)
We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight
4 min read
Iterative Depth First Traversal of Graph
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal (DFS) of a tree. The only catch here is, unlike trees, graphs may contain cycles, so a node might be visited twice. To avoid processing a node more than once, use a boolean visited array. Example: Input: n = 4, e = 6 0
15+ min read
BFS for Disconnected Graph
In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s
14 min read
Transitive Closure of a Graph using DFS
Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: Transit
8 min read
Difference between BFS and DFS
Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search. ParametersBFSDFSStands forBFS stands for Breadth First Search.DFS st
2 min read
Cycle in a Graph
Detect Cycle in a Directed Graph
Given the root of a Directed graph , The task is to check whether the graph contains a cycle or not. Examples: Input: V = 4, E = 6 Output: Yes Explanation: The diagram clearly shows a cycle 0 -> 2 -> 0 Input: V = 4, E = 4 Output: No Explanation: The diagram clearly shows no cycle. [Expected Ap
14 min read
Detect cycle in an undirected graph
Given an undirected graph, the task is to check if there is a cycle in the given graph. Examples: Input: V = 4, E = 4 Output: Yes Explanation: The diagram clearly shows a cycle 0 to 2 to 1 to 0 Input: V = 4, E = 3 Output: No Explanation: There is no cycle in the given graph. Using Breadth First Sear
9 min read
Detect Cycle in a directed graph using colors
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. Example: Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 Output: Yes Explanation: This dia
11 min read
Detect a negative cycle in a Graph | (Bellman Ford)
Given a directed weighted graph, the task is to find whether the given graph contains any negative-weight cycle or not. Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value. Example: Input: Output: No Input: Output: Yes Algorithm to Find Negative Cycle in a Directe
15+ min read
Cycles of length n in an undirected and connected graph
Given an undirected and connected graph and a number n, count the total number of simple cycles of length n in the graph. A simple cycle of length n is defined as a cycle that contains exactly n vertices and n edges. Note that for an undirected graph, each cycle should only be counted once, regardle
10 min read
Detecting negative cycle using Floyd Warshall
We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative. Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some adva
12 min read
Clone a Directed Acyclic Graph
A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ |
12 min read