Understanding the Problem
In a directed graph, a cycle occurs when a node eventually points back to itself through a sequence of directed edges. To detect this, we use Kahn’s Algorithm, which is typically used for topological sorting but can also be used for cycle detection.
Step-by-Step Explanation
We start by calculating the in-degree (number of incoming edges) for every node. Nodes with zero in-degree are not dependent on any other node and can be processed first.
We use a queue to keep track of these zero in-degree nodes. As we process a node, we reduce the in-degree of its neighbors. If any of these neighbors reach zero in-degree, they are added to the queue.
We also keep a counter (visitedCount
) to track how many nodes we have processed in this way.
Case 1: No Cycle Exists
If the graph has no cycles, eventually every node will be processed, and the visitedCount
will equal the total number of nodes. This means we were able to complete a topological sort, indicating no cycles.
Case 2: Cycle Exists
If there is a cycle, some nodes will always have a non-zero in-degree, because they are dependent on each other. These nodes will never enter the queue, so visitedCount
will be less than the total number of nodes. This tells us a cycle exists.
Example
Consider a graph with edges: 0 → 1, 1 → 2, 2 → 0. All nodes are part of a cycle. No node has zero in-degree, so the queue is initially empty. visitedCount
stays 0, and we detect a cycle.
Now consider a graph with edges: 0 → 1, 1 → 2. This has no cycle. Nodes will be processed one by one (0, then 1, then 2), and visitedCount
becomes 3 (equal to number of nodes). No cycle is detected.