(Translated by https://www.hiragana.jp/)
Detect Cycle in a Directed Graph - GeeksforGeeks
Open In App

Detect Cycle in a Directed Graph

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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]]

1
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]

directed-1
No Cycle

Output: 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 Python C# JavaScript

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 Python C# JavaScript

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.



Detect Cycle in a Directed graph using colors

Similar Reads