1. Kahn's Algorithm (BFS In-Degree Topological Sort)
Intuition
In a Directed Acyclic Graph (DAG), at least one vertex must have in-degree 0. Removing in-degree 0 vertices iteratively must consume all V vertices. If a cycle exists, the vertices in the cycle have mutually dependent edges and their in-degrees never reach 0, meaning total processed vertices < V.
Algorithm
- Compute in-degrees of all V vertices.
- Enqueue all vertices with inDegree[u] == 0 into queue q.
- Initialize count = 0.
- While queue is not empty:
- Pop u from q, count++.
- For each neighbor v in adj[u]:
- inDegree[v]--.
- If inDegree[v] == 0: push v into q.
- Return count < V (if fewer than V vertices processed, cycle exists).
#include <iostream>#include <vector>#include <queue> class Solution {public: bool isCyclic(int V, std::vector<std::vector<int>>& adj) { std::vector<int> inDegree(V, 0); for (int u = 0; u < V; ++u) { for (int v : adj[u]) { inDegree[v]++; } } std::queue<int> q; for (int i = 0; i < V; ++i) { if (inDegree[i] == 0) { q.push(i); } } int count = 0; while (!q.empty()) { int u = q.front(); q.pop(); count++; for (int v : adj[u]) { inDegree[v]--; if (inDegree[v] == 0) { q.push(v); } } } return count < V; // Cycle exists if topological sort incomplete }}; int main() { Solution sol; std::vector<std::vector<int>> adj = {{1}, {2}, {3}, {1}}; std::cout << "Kahn's Cycle: " << (sol.isCyclic(4, adj) ? "true" : "false") << " (Expected: true)\n"; return 0;}Time & Space Complexity
- Time complexity:
O(V + E) - Space complexity:
O(V)