How it works?
Lesson 3 of 9 in Coddy's Topological Sort - Graph Algorithms course.
The key quantity is a vertex's in-degree: how many edges point into it. A vertex with in-degree 0 has no unmet prerequisites, so it can go next.
Kahn's Algorithm:
- Compute the in-degree of every vertex.
- Pick the smallest vertex whose in-degree is 0, append it to the order, and "remove" it.
- Removing it decreases the in-degree of each of its out-neighbors by one (some may now reach 0).
- Repeat until no in-degree-0 vertex remains. If you placed all
nvertices, that is your topological order; if not, the graph has a cycle.
Example with edges [0,1, 0,2, 1,3, 2,3]: start with 0 (in-degree 0), then 1, then 2, then 3, giving [0, 1, 2, 3].
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Topological Sort - Graph Algorithms
2The Algorithm
How it works?Pseudo CodeImplementation (Part 1)Implementation (Part 2)