C++ Program to Check Cycle in a Graph using Topological Sort



In this problem, we are given adjacency lists of a directed graph and we need to check if there is a cycle in the graph using topological sort. If a cycle exists, it is not possible to perform a topological sort.

Example:

// Input Graph ( as adjacency list )
0 -> 1
1 -> 2
1 -> 3
2 -> 0

Output: Cycle exists
Explanation: The graph has a cycle (0 -> 1 -> 2 -> 0).

To solve this problem, we can use Khan's Algorithm, which is a BFS based topological sorting algorithm. To understand the algorithm, first let's learn what is a topological sort.

What is Topological Sort?

Topological Sort is an operation performed to check if a graph is a directed acyclic graph (DAG). In this operation we order the vertices in such a way that for every directed edge u ? v, vertex u comes before vertex v in the ordering. This operation cannot be performed on graphs with cycles. The image below show how a topological sort is performed on a directed acyclic graph.

Topological Sort

The topological sorting order should start from the vertex with no incoming edges and end at the vertex with no outgoing edges. In this case, the order of the vertices is 0 -> 4 -> 1 -> 2 -> 3.

Algorithm to Check Cycle in a Directed Graph using Topological Sort

The following steps implements Kahn's Algorithm to check if a directed graph is a DAG or not:

  • Step 1: Declare an array indegree to keep track of the in-degree of each vertex.
  • Step 2: Calculate the in-degree for all vertices by using the adjacency list of the graph.
  • Step 3: Insert all vertices with in-degree 0 into a queue.
  • Step 4: Start running a while loop to remove vertices from the queue and decrease the in-degree of their neighbors. If a neighbor's in-degree becomes 0, add it to the queue.
  • Step 5: If we are able to visit all vertices, the graph is a DAG. If not, it has a cycle.
Note: The in-degree of a vertex is the number of edges coming into that vertex.

C++ Program to Check Cycle in a Directed Graph

The code below implements above algorithm in C++ language. It creates a directed graph and checks whether it is a DAG or not.

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

bool isDAG(int V, vector<vector<int>>& adj) {
    vector<int> indegree(V, 0);

    for (int u = 0; u < V; u++) {
        for (int v : adj[u]) {
            indegree[v]++;
        }
    }

    queue<int> q;
    for (int i = 0; i < V; i++) {
        if (indegree[i] == 0) q.push(i);
    }

    int count = 0;
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        count++;

        for (int neighbor : adj[node]) {
            indegree[neighbor]--;
            if (indegree[neighbor] == 0) q.push(neighbor);
        }
    }

    return (count == V);
}

int main() {
    int V = 6;
    vector<vector<int>> adj(V);

    // Example Graph
    adj[5].push_back(2);
    adj[5].push_back(0);
    adj[4].push_back(0);
    adj[4].push_back(1);
    adj[2].push_back(3);
    adj[3].push_back(1);

    if (isDAG(V, adj)) {
        cout << "The graph is a DAG." << endl;
    } else {
        cout << "The graph contains a cycle." << endl;
    }

    return 0;
}

The output of the above code will be:

The graph is a DAG.

Time and Space Complexity

Time Complexity: The time complexity of this algorithm is O(n + m), where n is the number of vertices and m is the number of edges in the graph. This is because we are iterating through all vertices and edges to calculate the in-degrees and then processing each vertex once.

Space Complexity: The space complexity is O(n), where n is the number of vertices in the graph, as we are using an array to store the in-degrees and a queue for processing vertices.

Farhan Muhamed
Farhan Muhamed

No Code Developer, Vibe Coder

Updated on: 2025-06-16T18:14:11+05:30

425 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements