The Wayback Machine - https://web.archive.org/web/20250402203403/https://www.geeksforgeeks.org/detect-cycle-in-a-graph/
Open In App

Detect Cycle in a Directed Graph

Last Updated : 14 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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

Input-Directed-Graph

Output: Yes
Explanation: The diagram clearly shows a cycle 0 -> 2 -> 0

Input: V = 4, E = 4

Input-Directed-Graph--2

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");
}

Output
Graph 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");
}

Output
Graph 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)



Next Article

Similar Reads

three90RightbarBannerImg