Kahn’s Algorithm and Cycle Detection in Directed Graphs
dev.to·11h·
Discuss: DEV
Flag this post

Kahn’s algorithm is quite simple and intuitive. We just calculate the indegree of each node in the graph and start with those that have an indegree of 0 (by pushing them into the queue). Next, we take the nodes out of the queue one by one, iterate over their neighbors, and simulate edge removal by simply decreasing the indegree of each neighbor by 1. If during that process the indegree of any neighbor becomes 0, we push that node into the queue.

A simple analogy is the process of removing bricks from a pile — start from the top and keep removing those that have no one above them, and continue until the pile is empty.

This awesome creature named Kahn’s algorithm is not limited to just performing a topological sort. Along with that, it naturally detects a cycle for us (yes, a “2-i…

Similar Posts

Loading similar posts...