Topological Sort in Python
Chapter 52: Topological Sort
4 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Directed acyclic graphs: things that must come first
A DAG is a directed graph with no cycle, and a topological order lists its vertices so that every arrow a → b has a before b; every DAG has at least one, and a graph with a cycle has none.
Kahn's algorithm: take what has no prerequisites left
Kahn's algorithm works out every in-degree, puts the vertices with in-degree 0 in a ready pool, and repeatedly takes one, appends it to the order and lowers the in-degree of each vertex it points to, adding any that reach 0 to the pool.
Topological order by DFS: finish last, go first
Run DFS along the arrows, append each vertex to a list when it finishes (after all its arrows have been followed), and the reversed list is a topological order.
Cycles: when no order exists
During DFS, keep each vertex marked on path while you are inside it; an arrow to a vertex still on the path closes a cycle, while an arrow to a vertex already done is harmless.