Topological sort
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Some jobs have to wait for others: socks before shoes, a library before the program that uses it, a course before the course that needs it. A topological sort lists the jobs so that every "comes first" arrow points forward. Step through Kahn's algorithm on six getting-dressed jobs: count the arrows into each job, queue the jobs at 0, and cross out arrows as jobs are written down. Then add one wrong arrow and watch the run stop short, which is how the algorithm spots a cycle. The Software lessons "Graphs" and "Graph search: BFS and DFS" and the Maths lesson "Graph theory: vertices, edges and breadth-first search" cover directed graphs, queues and depth-first search; "DFS in depth: discovery times and cycle detection" shows the depth-first way to the same answer.
Jobs with arrows
Getting dressed is six jobs. An arrow from socks to shoes means socks must come first. Arrows that point one way, with no loop back, form a DAG: a directed acyclic graph. We want a list of jobs where every arrow points forward.
a DAG: directed edges, no directed cycle
u -> v means "u before v"
socks -> shoes
pants -> shoes
pants -> belt
shirt -> belt
shirt -> jacket
belt -> jacket
the same graph in Python (each job lists the jobs that wait for it):
graph = {
"socks": ["shoes"],
"pants": ["shoes", "belt"],
"shirt": ["belt", "jacket"],
"shoes": [],
"belt": ["jacket"],
"jacket": [],
}اقرأ الدرس خطوة بخطوة
Jobs with arrows
Getting dressed is six jobs. An arrow from socks to shoes means socks must come first. Arrows that point one way, with no loop back, form a DAG: a directed acyclic graph. We want a list of jobs where every arrow points forward.
a DAG: directed edges, no directed cycle u -> v means "u before v" socks -> shoes pants -> shoes pants -> belt shirt -> belt shirt -> jacket belt -> jacket the same graph in Python (each job lists the jobs that wait for it): graph = { "socks": ["shoes"], "pants": ["shoes", "belt"], "shirt": ["belt", "jacket"], "shoes": [], "belt": ["jacket"], "jacket": [], }Count the arrows coming in
For each job, count the arrows that point into it. That number is its in-degree: how many jobs it still waits for. Socks, pants and shirt wait for nothing (0). Shoes, belt and jacket each wait for 2.
in-degree = number of arrows coming in socks 0 · pants 0 · shirt 0 · shoes 2 · belt 2 · jacket 2 indeg = {u: 0 for u in graph} for u in graph: for v in graph[u]: indeg[v] += 1Zero means ready
A job with in-degree 0 can start now. Put every such job in a queue, in the order the graph lists them: socks, pants, shirt. A queue is a line: the first job in is the first job out.
ready = deque(u for u in graph if indeg[u] == 0) ready: [socks, pants, shirt] a deque appends and pops at either end in O(1) dicts keep insertion order, so the queue starts socks, pants, shirtTake one, cross out its arrows
The loop: take the front job and write it down. Socks is first. Then cross out its outgoing arrows: each crossed arrow lowers the count of the job it pointed to. Shoes drops from 2 to 1, so it still waits.
u = ready.popleft() # socks order.append(u) # order: [socks] for v in graph["socks"]: # shoes indeg["shoes"] -= 1 # 2 -> 1, not ready yetA count hits zero
Take pants and write it down. Its arrow to shoes is crossed out: shoes drops from 1 to 0, so shoes joins the back of the queue. Its arrow to belt is crossed out too: belt drops from 2 to 1.
u = pants order: [socks, pants] indeg["shoes"]: 1 -> 0 ready.append("shoes") indeg["belt"]: 2 -> 1 ready: [shirt, shoes]Shirt frees the belt
Take shirt. Belt drops from 1 to 0 and joins the queue, behind shoes. Jacket drops from 2 to 1: it still waits for the belt. A job enters the queue only when everything before it is written down.
u = shirt order: [socks, pants, shirt] indeg["belt"]: 1 -> 0 ready.append("belt") indeg["jacket"]: 2 -> 1 ready: [shoes, belt]Empty the queue
Shoes has no outgoing arrows, so taking it changes nothing. Taking belt drops jacket to 0, and jacket is taken last. The queue is empty and all six jobs are written down.
u = shoes (no arrows out) u = belt indeg["jacket"]: 1 -> 0 ready.append("jacket") u = jacket (no arrows out) order: [socks, pants, shirt, shoes, belt, jacket]Every arrow points forward
Number the jobs by their place in the list. Every arrow goes from a smaller number to a bigger one: that is a topological order. It is not the only one. Shirt, socks, pants, belt, shoes, jacket also works.
topological order: f(u) < f(v) for every arrow u -> v socks 1 -> shoes 4 pants 2 -> shoes 4 pants 2 -> belt 5 shirt 3 -> belt 5 shirt 3 -> jacket 6 belt 5 -> jacket 6 another valid order: shirt, socks, pants, belt, shoes, jacket socks and pants are not joined by an arrow, so either may go firstLinear time: O(V + E)
Each job enters and leaves the queue once: V = 6 times. Each arrow is counted once and crossed out once: E = 6 arrows. So the work grows like V + E, written O(V + E), the same as one BFS or DFS.
V = 6 jobs: 6 appends + 6 popleft calls E = 6 arrows: 6 "+= 1" + 6 "-= 1" each step is O(1) (dict lookup, deque append and popleft) total: O(V + E)A loop means no order
Add a wrong arrow: jacket before shirt. Now shirt, belt and jacket each wait for another in a loop. No count reaches 0, so the run stops with 3 of 6 jobs written. A short list means the graph has a cycle.
extra arrow: jacket -> shirt loop: shirt -> belt -> jacket -> shirt order: [socks, pants, shoes] (3 of 6) left waiting: shirt 1 · belt 1 · jacket 2 if len(order) < len(graph): raise ValueError("cycle")
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01In the lesson's graph, what is the in-degree of belt?
Two arrows point into belt: pants → belt and shirt → belt. Its own arrow to jacket goes out, so it does not count.
02In Kahn's algorithm, when does a job join the ready queue?
A job is ready only when nothing it waits for is left: its count of incoming arrows is 0. At the start that is socks, pants and shirt; shoes joins after pants is written down.
03Which of these is NOT a valid topological order of the lesson's graph?
In the last option shoes comes before pants, but the arrow pants → shoes says pants must come first. Belt also comes before shirt, which breaks shirt → belt. The other three keep every arrow pointing forward.
04Kahn's algorithm finishes with fewer jobs in the order than there are in the graph. What does that tell you?
Jobs on a loop of arrows each wait for another job on the loop, so none of their counts ever reaches 0 and they never enter the queue. No topological order exists.
05A graph has V jobs and E arrows. How much work does Kahn's algorithm do?
Each job enters and leaves the queue once (V), and each arrow is counted once and crossed out once (E). With O(1) dict and deque operations the total is O(V + E).
المسرد
- Directed graph
- Nodes joined by arrows. An arrow u → v goes one way only; here it means u must come before v.
- DAG
- A directed acyclic graph: a directed graph with no loop of arrows that leads back to where it started.
- Topological order
- A list of all the nodes in which every arrow goes from an earlier node to a later one.
- In-degree
- The number of arrows pointing into a node: how many jobs it still waits for.
- Kahn's algorithm
- Queue every node with in-degree 0; repeatedly take one, write it down and remove its outgoing arrows, queueing any node whose in-degree drops to 0.
- Queue
- A line of items where the first one in is the first one out. Python's collections.deque is a fast queue.
- Cycle
- A path of arrows that returns to its starting node. A graph with a cycle has no topological order.
الملاحظات والمصادر
- This queue method is Kahn's algorithm (A. B. Kahn, 1962). Another way, in MIT 6.006 and Sedgewick and Wayne, runs depth-first search and lists the jobs in reverse finishing order; both take O(V + E) time.
- A directed graph has a topological order exactly when it is a DAG: a directed acyclic graph, with no loop of arrows (Sedgewick and Wayne, §4.2).
- The order is unique only when every pair of neighbours in the list is joined by an arrow. Here socks, pants and shirt are all ready at the start, so several orders are correct; the queue picks the one the graph lists first.
- The code is real Python 3. Python's standard library has the same tool: graphlib.TopologicalSorter. Its dict maps each job to the jobs it waits for (the reverse of ours), and it raises CycleError on a loop.
- The getting-dressed example is adapted from Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, §20.4 (4th ed.), which uses more garments.
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 10: Depth-First Search (topological sort, cycle detection)
- Sedgewick and Wayne, Algorithms 4th ed., §4.2 Directed Graphs (topological order and DAGs)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §20.4 Topological sort
- Topological sorting (Kahn's algorithm; A. B. Kahn, Communications of the ACM 5(11), 1962)
- Python docs: graphlib.TopologicalSorter
- Python docs: collections.deque
- Python docs: dict keeps insertion order
اختبار يتاح بعد الخطوة الأخيرة.