← capítulo

Topological sort

Order a DAG so every arrow points forward: prerequisites first. Exists iff there's no cycle.

Two algorithms, both familiar

Watch Kahn peel the graph

Green = ready (in-degree 0) · orange = placing · dark = blocked (shows remaining in-degree). The ready frontier sweeps left to right.

Guessing almost never works

12 edges → 1 in ~741 random orders is valid. Topo sort: valid every time, O(V+E).

The order isn't unique

Takeaway

graphlib.TopologicalSorter ships with Python 3.9+ — batteries included. No valid order ⇒ your dependencies have a cycle (often the real finding). Next: weights break the "every edge = one step" assumption → Dijkstra.