Graph Theory37 sections · 1633 units
Open in Course

Detecting Cycles with Kahn's

The Leftovers

If the queue becomes empty but you have not processed all NN nodes (order.size < n), it means the remaining nodes form a cycle. They all have in-degree 1\geq 1 pointing at each other, so none could enter the queue.

This is how you solve Course Schedule. It is exactly the same code, printing "IMPOSSIBLE" if the size check fails. Kahn's algorithm naturally detects cycles without needing a three-state DFS tracker.