Topological order
how it works
The idea on a small map, then the whole method on the watch page's first map.
Topological order puts places in an order where every one-way road runs forwards, from an earlier place to a later one. A road from A to B says A must come before B, as one task must finish before the next can start. Write at each place how many roads come into it, its count. Places with a count of 0 are free to go first, so they join a queue. Take the place at the front: the next number replaces its count. Cross off each road from it, so the place that road leads to has one fewer coming in. A place with none left joins the back of the queue. Places free at the start, or freed by the same place, join in letter order, only so this page has one answer: any order would be right. If the queue empties with places not taken, each sits on a loop, roads leading round to where they began, or after one, reached from a loop. No order can hold them. This page counts the roads crossed off. The code below, in the language Python, does the same. Where the code says sorted, that only keeps letter order, and the method needs no sort.
| takes next | its number | roads crossed off | joins the queue | queue after |
|---|---|---|---|---|
| start | A | A | ||
| A | 1 | A to B, A to E | B, E | B, E |
| B | 2 | B to C, B to F | C | E, C |
| E | 3 | E to F | F | C, F |
| C | 4 | none | F | |
| F | 5 | none |
step 1 of 20
Write at each of the 8 places how many roads come into it. Those with none, A, join the queue.
what it remembers to know where it is
- taken last
- not yet
- next number
- 1
Where it says not yet, nothing is held there at that moment.
step 2 of 20
A is at the front of the queue, so it takes number 1 in the order.
what it remembers to know where it is
- taken last
- A
- next number
- 2
step 3 of 20
Cross off the road from A to B: B still has one road coming in.
what it remembers to know where it is
- taken last
- A
- next number
- 2
step 4 of 20
Cross off the road from A to E. No road is left coming into E, so it joins the back of the queue.
what it remembers to know where it is
- taken last
- A
- next number
- 2
step 9 of 20
Cross off the road from F to G. No road is left coming into G, so it joins the back of the queue.
what it remembers to know where it is
- taken last
- F
- next number
- 4
step 10 of 20
B is at the front of the queue, so it takes number 4 in the order.
what it remembers to know where it is
- taken last
- B
- next number
- 5
step 11 of 20
Cross off the road from B to C: C still has one road coming in.
what it remembers to know where it is
- taken last
- B
- next number
- 5
step 20 of 20
Done: every place is in order, 8 in all, and every road runs from a smaller number to a bigger one.
what it remembers to know where it is
- taken last
- not yet
- next number
- 9
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- write at each place how many roads come into it; those with none join the queuePython lines 15, 16, 17, 18, 19, 20, 21 and 22
- while the queue is not empty, the place at its front takes the next number in the orderPython lines 24, 25, 26 and 27
- cross off each road from it: the place it leads to has one road fewer coming inPython lines 28 and 29
- a place with no road left coming in joins the back of the queuePython lines 30 and 31
- every place numbered: that is an order in which every road runs forwardsPython line 33
- places left over sit on a loop, or after one, and have no orderPython line 32
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
from collections import deque
def topological_order(roads):
"""Put the places in an order where every one-way road runs forwards.
roads is a list of pairs (from, to), such as ("A", "B"). Returns a dict,
a table, of what each place has written at the end: its number in the
order, or, if it sits on a loop or after one, the roads still coming in.
"""
return take_from_queue(roads)[0]
def take_from_queue(roads):
written = {} # how many roads come into each place
going_out = {} # each place's roads out
for a, b in roads:
written.setdefault(a, 0)
written[b] = written.get(b, 0) + 1
going_out.setdefault(a, []).append(b)
# sorted keeps the watch page's letter order; any order is right
queue = deque(place for place in sorted(written) if written[place] == 0)
order = []
while queue: # while the queue is not empty
here = queue.popleft() # the place at its front
order.append(here)
written[here] = len(order) # takes the next number
for there in sorted(going_out.get(here, [])): # cross off each road from it
written[there] -= 1 # one road fewer coming in
if written[there] == 0: # none left
queue.append(there) # so it joins the back of the queue
left = sorted(set(written) - set(order)) # each sits on a loop, or after one
return written, order, left # with none left, every road runs forwards
how it scales
The plot counts the roads crossed off on two maps with no loop. One is a line of places, each leading to the next. The other lists its places and joins every pair, each road from the earlier in the list to the later. is how many places, measured from 10 to 1,000.
Each mark across or up is ten times the one before. A line of places climbs one mark up for each mark across: 99 at 100 places and 999 at 1,000, about 10 times. Every pair joined climbs two: 4,950 at 100 places and 499,500 at 1,000, about 101 times. A slope of 1 means the cost grows as , and a slope of 2 as the square of .
roads crossed off, ten times more at each mark up
, n, ten times more at each mark to the right
- every pair joinedsolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
- a linesolid where measured by running it; dashed where its formula carries it on to ten million
| roads crossed off | time | |
|---|---|---|
| 1,000 | 499,500 | about 500 microseconds |
| 100,000 | 4,999,950,000 | about 5 seconds |
| 10,000,000 | 49,999,995,000,000 | about 14 hours |
The roads crossed off are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count topological order's roads crossed off yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it runs two maps of n
places with no loop: a line, the fewest roads that join them, and every two
places joined, the most. It prints the roads crossed off for each. The
counts are the same on any computer; only the time differs.
"""
from collections import deque
def topological_order(roads):
"""Put the places in an order where every one-way road runs forwards.
roads is a list of pairs (from, to), such as ("A", "B"). Returns a dict,
a table, of what each place has written at the end: its number in the
order, or, if it sits on a loop or after one, the roads still coming in.
"""
return take_from_queue(roads)[0]
def take_from_queue(roads):
written = {} # how many roads come into each place
going_out = {} # each place's roads out
for a, b in roads:
written.setdefault(a, 0)
written[b] = written.get(b, 0) + 1
going_out.setdefault(a, []).append(b)
# sorted keeps the watch page's letter order; any order is right
queue = deque(place for place in sorted(written) if written[place] == 0)
order = []
while queue: # while the queue is not empty
here = queue.popleft() # the place at its front
order.append(here)
written[here] = len(order) # takes the next number
for there in sorted(going_out.get(here, [])): # cross off each road from it
written[there] -= 1 # one road fewer coming in
if written[there] == 0: # none left
queue.append(there) # so it joins the back of the queue
left = sorted(set(written) - set(order)) # each sits on a loop, or after one
return written, order, left # with none left, every road runs forwards
def count(roads):
"""How many roads the run crosses off: every road from a place taken."""
taken = set(take_from_queue(roads)[1])
return sum(1 for a, _ in roads if a in taken)
def line(n):
"""n places in a line, each leading to the next: n - 1 roads."""
return [(k, k + 1) for k in range(1, n)]
def every_pair(n):
"""n places, every two joined, from the smaller to the bigger: n(n - 1) / 2 roads."""
return [(a, b) for a in range(1, n + 1) for b in range(a + 1, n + 1)]
if __name__ == "__main__":
print(f"{'n':>6} {'a line':>8} {'every pair':>12}")
for n in [10, 100, 1000]:
print(f"{n:>6} {count(line(n)):>8} {count(every_pair(n)):>12}")
best, worst and average
Here best just names a line and worst names every pair: kinds of map with no loop. A line is not the fewest a run can cross off: a loop can stop a run sooner, and a ring of 4 crosses off none. Every pair is the most a map with no loop can hold. No average is worked out. With 8 places a run crosses off 7 on a line, 10 on the first map and 28 with every pair joined.
A case is one kind of map, such as a line, however many places. A bound says how fast that case's cost grows as more places are added.
The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.
| besta line | worstevery pair joined | |
|---|---|---|
| roads crossed off | , each road once | , each road once |
| places put in order | , every place | , every place |
| how the roads crossed off grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: A count at each place, a queue of at most places, and each place's list of roads out.
Extra memory is the room it needs on top of the input itself, while it runs.
| map | places | roads | crossed off | taken |
|---|---|---|---|---|
| a line of 5 | 5 | 4 | 4 | 5 |
| every pair of 5 | 5 | 10 | 10 | 5 |
| the first map | 8 | 10 | 10 | 8 |
| a ring of 4 | 4 | 4 | 0 | 0 |
where the formula comes from
Questions 1 and 2 say what a run does on any map, 3 and 4 count the two kinds, 5 the whole method, and 6 why every road runs forwards.
the move: a place joins once
the line:place roads coming in joins the queue at number A 0 the start 1 B 1 A to B 2 E 1 A to E 3 C 1 B to C 4 F 2 E to F 5 The small map. F has 2 roads in, and joins only when the second, E to F, is crossed off. why it is allowed: A count only falls, one road at a time, so it falls to 0 at most once. A place starting at 0 has no road in, so its count never moves.
the move: a place is taken once
the line:why it is allowed: A place leaves the queue only to be taken, and by line 1 it joined at most once.
guess it, thenthe move: a road is crossed off once
the line:why it is allowed: A road is crossed off only when the place it leaves is taken, and by line 2 that happens at most once. So at most roads are crossed off, and is that ceiling. A loop can leave some uncrossed.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: when the queue empties
the line:why it is allowed: Suppose the queue is empty and places are not taken. Each still has a count above 0, or it would have joined. A road from a place taken was crossed off, so a road not crossed off comes from a place not taken.
the move: walk back
the line:why it is allowed: Start at a place not taken and go backwards along a road not crossed off. By line 1 you reach another place not taken, which has such a road too, so the walk never has to stop.
guess it, thenthe move: a place comes twice
the line:A is taken, shaded, and the queue empties. Walk back from C: B, E, F, then B again. Read forwards, B to F, F to E and E to B, heavy, is a loop, and C sits after it. why it is allowed: There are only places, so a walk that never stops comes back to one. The roads between its two visits make a loop, and the place you started from sits on it or after it.
guess it, thenthe move: no loop, none left
the line:why it is allowed: With no loop, by line 3 every place is taken, all . Each crosses off all its roads, so every road is crossed off. For 5 places, 5.
guess it, thenthe move: a loop, no order
the line:why it is allowed: Round any loop, as here, an order would need B before F, F before E and E before B, so B before itself. So stopping is the right answer, and places not taken mean a loop.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: every road, once
the line:A line of 5. Each of its 4 roads is crossed off once, and only one order fits. why it is allowed: A line has no loop, so by question 2 every road is crossed off, and by question 1 only once. The first place needs no road, and each place after it adds one. For 5 places, 4.
the move: a ceiling
the line:why it is allowed: is below . For 5 places, is 4, at most 5.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 2, with the fixed multiple 1. reads is in, and means at most a fixed multiple of , from some on.
guess it, thenthe move: a floor
the line:why it is allowed: From 2 places on, is at least half of . For 5 places, is 4, at least 2.5.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple a half. means at least a fixed multiple of , above 0, from some on.
guess it, thenthe move: both together
the line:why it is allowed: Lines 3 and 5 bound by the same growth. means both.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: place by place
the line:every pair of 5 crossed off A 4 B 3 C 2 D 1 E 0 all 10 Each place's roads to the places after it. why it is allowed: Each road runs from earlier in the list to later, so none leads back, and there is no loop. By question 2 every place is taken. Every two are joined, so only one order fits. The first place crosses off a road to each of the after it, the next , and the last none.
the move: how many roads
the line:where does this come from?
question 2 of the page graphs and their words places, every two joined by a road. How many roads? the move: count place by place
the line:Every two of 5 places joined. A has 4 roads, B 3 more, C 2 more, D 1 more, E none new. 4 + 3 + 2 + 1 = 10. why it is allowed: Let be the roads, for 2 places or more. List the places. The first has roads to the after it. The next adds one fewer new road, as its road to the first is counted already. Each adds one fewer, and the last adds none.
the move: use adding up 1 to n
the line:place new roads A 4 B 3 C 2 D 1 E 0 all 10 The new roads each place adds on line 1's map, in turn. 4 + 3 + 2 + 1 + 0 = 10. where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line:Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15. why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: Read from right to left, line 1 is 1 + 2 + up to . The box under this line adds 1 up to a last number with two staircases, that number times one more, halved. Here the last number is . One more than it is , so is times , halved. For 5, 1 + 2 + 3 + 4 is 4 times 5, halved, which is 10.
the move: one way, each pair holds two
the line:why it is allowed: Let be the most one-way roads. A to B and B to A are two roads, one each way, so each pair holds two.
the move: double line 2
the line:why it is allowed: Line 3 says is , and twice line 2 is . For 5 places, 20.
the move: read it
the line:why it is allowed: 1,000 times 999, halved, is 499,500. A map of 1,000 places with 3,000 roads has 3 times as many roads as places, a few, so it is sparse. It holds 3,000 of the 499,500 it could.
why it is allowed: How many roads every pair has, shown under this line. Two roads between one pair would run both ways, a loop, and the watch page refuses a road given twice, so with no loop this is the most. For 5 places, 10.
guess it, thenthe move: a ceiling
the line:why it is allowed: is below . For 5 places, is 10, at most 12.5.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 3, with the fixed multiple a half.
guess it, thenthe move: a floor
the line:why it is allowed: From 2 places on, is at least half of . For 5 places, is 10, at least 6.25.
guess it, thenthe move: read the bound
the line:From 2 places on, stays between its floor and its ceiling. why it is allowed: By line 5, with the fixed multiple a quarter.
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same growth.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: each road, twice
the line:why it is allowed: is a ceiling on the reads of roads. The first count reads each road once, to add 1 at its end. By question 1 crossing off reads it once more at most. For the small map, 10.
the move: each place, three times
the line:why it is allowed: The start looks once at each place's count. By question 1's lines 1 and 2, each place then joins the queue at most once and leaves at most once. For the small map, 15.
guess it, thenthe move: add them
the line:the small map count roads read 10 place steps 15 all 25 Five places and five roads, with no loop, so each ceiling is met. why it is allowed: Lines 1 and 2 added.
guess it, thenthe move: it needs lists
the line:why it is allowed: Crossing off reads only the taken place's own roads, so each place must list them, as the Python's going_out does. A grid has a row of cells for each place, read whole even with few roads. On the small map, crossing off reads 5 roads from lists, and 5 rows of 5 cells from a grid.
guess it, thenthe move: read the bound
the line:why it is allowed: is at most 3 times . On the small map, 25 is at most 30. A computer does each read or step in a fixed few actions, so the whole stays at most a fixed multiple of . A loop only stops the run sooner. On every pair, grows as the square of , as question 4's count does. In books is the places and the roads, not place E.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: the far end waits
the line:why it is allowed: Take any road, from A to B. B joins the queue only when no road is left coming in, and this road comes in.
the move: so the near end goes first
the line:why it is allowed: A to B is crossed off only when A is taken. So A has its number before B even joins the queue.
guess it, thenthe move: numbers only grow
the line:road its start's number its end's number A to B 1 2 A to E 1 3 B to C 2 4 B to F 2 5 E to F 3 5 The small map's five roads, each from a smaller number to a bigger one. why it is allowed: Each place taken gets the next number, so a place taken later has a bigger one. B is taken after A.
guess it, thenthe move: every road
the line:why it is allowed: Lines 1 to 3 used nothing about which road it was, and by question 2 every place is taken. So all run forwards.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
count it yourself
Every pair of 3 places: A, B and E. The watch page writes this map as A>B, A>E, B>E, where A>B means a road from A to B. A has 0 roads coming in, B has 1 and E has 2. A goes first. Crossing off A to B frees B, and A to E leaves E with 1. Then B goes, and B to E frees E. The last columns are running totals.
| step | the queue, front first | what happens | roads crossed off | places put in order |
|---|---|---|---|---|
| 1 | A | Write at each of the 3 places how many roads come into it. Those with none, A, join the queue.A | 0 | 0 |
| 2 | A is at the front of the queue, so it takes number 1 in the order. | 0 | 1 | |
| 3 | B | Cross off the road from A to B. No road is left coming into B, so it joins the back of the queue.B | 1 | 1 |
| 4 | B | Cross off the road from A to E: E still has one road coming in.B | 2 | 1 |
| 5 | B is at the front of the queue, so it takes number 2 in the order. | 2 | 2 | |
| 6 | E | Cross off the road from B to E. No road is left coming into E, so it joins the back of the queue.E | 3 | 2 |
| 7 | E is at the front of the queue, so it takes number 3 in the order. | 3 | 3 | |
| 8 | Done: every place is in order, 3 in all, and every road runs from a smaller number to a bigger one. | 3 | 3 |
In all, 3 roads crossed off. The formula from section 4, , gives at : the same.
where you meet it
A 1962 paper set it out, and ready-made code uses it to put tasks in order.
Kahn's 1962 paper
A. B. Kahn set out this way of ordering large networks, with project planning as an example. Take a task with nothing left before it, again and again.
source: A. B. Kahn, Topological sorting of large networks (opens in a new tab), Communications of the ACM 5(11), and the books' volume two, chapter 29
Python's graphlib
graphlib, in Python itself, counts what each task still waits for, and hands you all the tasks with none left. When you say one is done, it counts down the tasks waiting on it.
source: Python's documentation, graphlib (opens in a new tab); Python's own code, Lib/graphlib.py, its TopologicalSorter, get_ready and done
networkx's topological_generations
networkx, ready-made Python code for networks, counts the roads coming in and hands back the places in groups that can go at once.
source: the networkx source, dag.py (opens in a new tab), its topological_generations
what is used instead
When you want one order and the loop named, depth-first search does both, as section 7 sets out. On two-way roads no order exists, since a road would need each end before the other, so this method is for one-way maps.
how it compares
Depth-first search, a deep walk, follows roads as far as they go, then backs up. A place finishes when none of its roads leads anywhere new. Write each place as it finishes, and read the list backwards. Along a road, the far end is one of three. New, so it finishes before the walk backs up, as F on B to F in the walk drawn below. Finished already, as F on E to F. Or met but not finished, which means the walk came from it to here and has not backed up, so this road makes a loop. So with no loop, backwards the near end comes first. If places are not yet met when the walk ends, start again from one. It visits each place once and looks along each road once, so it is in too.
| method | takes next | on a loop | also gives |
|---|---|---|---|
| this page's queue | a place with no road left coming in | stops with places not taken | layers of places that can go at once |
| a deep walk read backwards | the walk's next road | meets a road back to a place not finished; the way from there to here, with that road, is the loop | one order and no layers |