Detect Cycle in Directed Graph (BFS)
Detect a cycle in a directed graph using Kahn's in-degree peeling.
Open on GeeksforGeeks ↗Intuition
Run a topological sort and see whether it finishes. Vertices with no incoming edges can always be peeled away; each removal may free others. A vertex inside a cycle is always waiting on another vertex in that same cycle, so its in-degree never reaches zero. If the peeling ends before all V vertices are removed, whatever is left is exactly the cyclic part.
Approach
Reuse Kahn's machinery
Compute in-degrees, queue the zeros, and peel. Only the final check differs from a plain topological sort.
Count what came out
Track how many vertices were peeled. If that count is less than V, a cycle exists — no extra bookkeeping needed.
BFS vs DFS for this
Kahn's needs no recursion and no colours, which makes it the safer choice on very deep graphs; the DFS/grey version is better when you also want the actual cycle.
Solution & live demo
Edge cases
All V vertices peel — no cycle.
The acyclic part peels, the cyclic part stalls, count falls short.
That vertex's in-degree includes itself and never reaches 0.