Skip to content

Topological order

networks

Level 2 of 3

Also called Topological sort and Kahn's algorithm.

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.

A0B1C1E1F2
Five one-way roads. Above each place, how many roads come into it. A has 0 and F has 2.
takes nextits numberroads crossed offjoins the queuequeue after
startAA
A1A to B, A to EB, EB, E
B2B to C, B to FCE, C
E3E to FFC, F
C4noneF
F5none
The order A, B, E, C, F. All 5 roads are crossed off, each once.
A1B2C4E3F5
Each place shows its letter and its number. Every road runs from a smaller number to a bigger one.
Ten roads, no loop: 8 moments of its 20 steps, the steps between them left for the watch page
  1. step 1 of 20

    A0B2C2D2E1F1G1H1A

    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.

    watch from here

  2. step 2 of 20

    A1B2C2D2E1F1G1H1

    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

    watch from here

  3. step 3 of 20

    A1B1C2D2E1F1G1H1

    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

    watch from here

  4. step 4 of 20

    A1B1C2D2E0F1G1H1E

    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

    watch from here

  5. step 9 of 20

    A1B0C2D2E2F3G0H1BG

    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

    watch from here

  6. step 10 of 20

    A1B4C2D2E2F3G0H1G

    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

    watch from here

  7. step 11 of 20

    A1B4C1D2E2F3G0H1G

    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

    watch from here

  8. step 20 of 20

    A1B4C6D8E2F3G5H7

    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.

    watch from here

the steps, in plain words
  1. 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
  2. while the queue is not empty, the place at its front takes the next number in the orderPython lines 24, 25, 26 and 27
  3. cross off each road from it: the place it leads to has one road fewer coming inPython lines 28 and 29
  4. a place with no road left coming in joins the back of the queuePython lines 30 and 31
  5. every place numbered: that is an order in which every road runs forwardsPython line 33
  6. 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. nn 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 nn, and a slope of 2 as the square of nn.

roads crossed off, ten times more at each mark up

a seconda minutean houra dayslope 2102104106108101010121014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107

nn, 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
how long every pair joined takes, at a billion roads a second
nnroads crossed offtime
1,000499,500about 500 microseconds
100,0004,999,950,000about 5 seconds
10,000,00049,999,995,000,000about 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
besta lineworstevery pair joined
roads crossed offn−1n - 1, each road oncen(n−1)2\frac{n(n - 1)}{2}, each road once
places put in ordernn, every placenn, every place
how the roads crossed off grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n2)\Theta(n^2)
ceiling, OOO(n)O(n)O(n2)O(n^2)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n2)\Omega(n^2)

extra memory: A count at each place, a queue of at most nn 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.

ABCDE
Every pair of 5, each road from the earlier letter to the later. Its 10 roads are each crossed off once.
A1B1E1F1
A ring of 4. Every place has 1 coming in, so nothing joins the queue and the run stops at once.
mapplacesroadscrossed offtaken
a line of 55445
every pair of 5510105
the first map810108
a ring of 44400
With no loop, a run crosses off every road and takes every place.

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.

Question 1: on any map of mm roads, how many can a run cross off? Let RR be a ceiling on them.
  1. the move: a place joins once

    the line:
    each place joins thequeue at most once\begin{gathered} \text{each place joins the} \\ \text{queue at most once} \end{gathered}
    placeroads coming injoins the queue atnumber
    A0the start1
    B1A to B2
    E1A to E3
    C1B to C4
    F2E to F5
    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.

  2. the move: a place is taken once

    the line:
    each place is takenat most once\begin{gathered} \text{each place is taken} \\ \text{at most once} \end{gathered}

    why it is allowed: A place leaves the queue only to be taken, and by line 1 it joined at most once.

  3. the move: a road is crossed off once

    the line:
    R=mR = m

    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 mm roads are crossed off, and RR is that ceiling. A loop can leave some uncrossed.

try it with a small mm: at m=5m = 5, line 3 gives R=5R = 5, which you can work out by hand

Question 2: why does a run number every place, on a map with no loop? Let TT be how many it numbers.
  1. the move: when the queue empties

    the line:
    each place not takenhas a road in froma place not taken\begin{gathered} \text{each place not taken} \\ \text{has a road in from} \\ \text{a place not taken} \end{gathered}

    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.

  2. the move: walk back

    the line:
    walking back meetsonly places not taken\begin{gathered} \text{walking back meets} \\ \text{only places not taken} \end{gathered}

    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.

  3. the move: a place comes twice

    the line:
    places not taken: on aloop, or after one\begin{gathered} \text{places not taken: on a} \\ \text{loop, or after one} \end{gathered}
    ABCEF
    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 nn 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.

  4. the move: no loop, none left

    the line:
    T=nT = n

    why it is allowed: With no loop, by line 3 every place is taken, all nn. Each crosses off all its roads, so every road is crossed off. For 5 places, 5.

  5. the move: a loop, no order

    the line:
    a loop: noorder at all\begin{gathered} \text{a loop: no} \\ \text{order at all} \end{gathered}

    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.

try it with a small nn: at n=5n = 5, line 4 gives T=5T = 5, which you can work out by hand

Question 3: how many roads, KK, does a line of nn places cross off?
  1. the move: every road, once

    the line:
    K=n−1K = n - 1
    ABCDE
    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.

  2. the move: a ceiling

    the line:
    K≤nK \le n

    why it is allowed: n−1n - 1 is below nn. For 5 places, KK is 4, at most 5.

  3. the move: read the bound

    the line:
    K∈O(n)K \in O(n)

    why it is allowed: By line 2, with the fixed multiple 1. ∈\in reads is in, and O(n)O(n) means at most a fixed multiple of nn, from some nn on.

  4. the move: a floor

    the line:
    K≥n2K \ge \frac{n}{2}

    why it is allowed: From 2 places on, n−1n - 1 is at least half of nn. For 5 places, KK is 4, at least 2.5.

  5. the move: read the bound

    the line:
    K∈Ω(n)K \in \Omega(n)

    why it is allowed: By line 4, with the fixed multiple a half. Ω(n)\Omega(n) means at least a fixed multiple of nn, above 0, from some nn on.

  6. the move: both together

    the line:
    K∈Θ(n)K \in \Theta(n)

    why it is allowed: Lines 3 and 5 bound KK by the same growth. Θ(n)\Theta(n) means both.

try it with a small nn: at n=5n = 5, line 1 gives K=4K = 4, which you can work out by hand

Question 4: how many roads, WW, does every pair of nn places cross off?
  1. the move: place by place

    the line:
    W=(n−1)+(n−2)+⋯+1+0W = (n - 1) + (n - 2) + \dots + 1 + 0
    every pair of 5crossed off
    A4
    B3
    C2
    D1
    E0
    all10
    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 n−1n - 1 after it, the next n−2n - 2, and the last none.

  2. the move: how many roads

    the line:
    W=n(n−1)2W = \frac{n(n - 1)}{2}
    where does this come from?
    question 2 of the page graphs and their wordsnn places, every two joined by a road. How many roads?
    1. the move: count place by place

      the line:
      R=(n−1)+⋯+2+1R = (n - 1) + \dots + 2 + 1
      ABCDE
      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 RR be the roads, for 2 places or more. List the places. The first has roads to the n−1n - 1 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.

    2. the move: use adding up 1 to n

      the line:
      R=n(n−1)2R = \frac{n(n - 1)}{2}
      placenew roads
      A4
      B3
      C2
      D1
      E0
      all10
      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 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
      1. the move: draw the sum as a staircase

        the line:
        S=1+2+⋯+nS = 1 + 2 + \dots + n

        why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

      2. the move: take two staircases

        the line:
        2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

        why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

      3. the move: fit them into a rectangle

        the line:
        2S=n(n+1)2S = n(n + 1)
        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 nn 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 n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

      4. the move: halve both sides

        the line:
        S=n(n+1)2S = \frac{n(n + 1)}{2}

        why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

      the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

      why it is allowed: Read from right to left, line 1 is 1 + 2 + up to n−1n - 1. 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 n−1n - 1. One more than it is nn, so RR is n−1n - 1 times nn, halved. For 5, 1 + 2 + 3 + 4 is 4 times 5, halved, which is 10.

    3. the move: one way, each pair holds two

      the line:
      one way:U is twice R\begin{gathered} \text{one way:} \\ U \text{ is twice } R \end{gathered}

      why it is allowed: Let UU be the most one-way roads. A to B and B to A are two roads, one each way, so each pair holds two.

    4. the move: double line 2

      the line:
      U=2R=n(n−1)U = 2R = n(n - 1)

      why it is allowed: Line 3 says UU is 2R2R, and twice line 2 is n(n−1)n(n - 1). For 5 places, 20.

    5. the move: read it

      the line:
      5 places: 10 roads, or 20 one way1,000 places: 499,500 roads\begin{gathered} 5 \text{ places: 10 roads, or 20 one way} \\ 1{,}000 \text{ places: } 499{,}500 \text{ roads} \end{gathered}

      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.

    the whole page: graphs and their words

    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.

  3. the move: a ceiling

    the line:
    W≤n22W \le \frac{n^2}{2}

    why it is allowed: n−1n - 1 is below nn. For 5 places, WW is 10, at most 12.5.

  4. the move: read the bound

    the line:
    W∈O(n2)W \in O(n^2)

    why it is allowed: By line 3, with the fixed multiple a half.

  5. the move: a floor

    the line:
    W≥n24W \ge \frac{n^2}{4}

    why it is allowed: From 2 places on, n−1n - 1 is at least half of nn. For 5 places, WW is 10, at least 6.25.

  6. the move: read the bound

    the line:
    W∈Ω(n2)W \in \Omega(n^2)
    roadsplaces010203040500246810roadsplaces010203040500246810
    • n22\frac{n^2}{2}
    • WW
    • n24\frac{n^2}{4}
    From 2 places on, WW stays between its floor and its ceiling.

    why it is allowed: By line 5, with the fixed multiple a quarter.

  7. the move: both together

    the line:
    W∈Θ(n2)W \in \Theta(n^2)

    why it is allowed: Lines 4 and 6 bound WW by the same growth.

try it with a small nn: at n=3n = 3, line 1 gives W=3W = 3, which you can work out by hand

Question 5: why does the whole method grow no faster than n+mn + m?
  1. the move: each road, twice

    the line:
    N=2mN = 2m

    why it is allowed: NN 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.

  2. the move: each place, three times

    the line:
    place steps:at most 3n\begin{gathered} \text{place steps:} \\ \text{at most } 3n \end{gathered}

    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.

  3. the move: add them

    the line:
    both together:at most 3n+2m\begin{gathered} \text{both together:} \\ \text{at most } 3n + 2m \end{gathered}
    the small mapcount
    roads read10
    place steps15
    all25
    Five places and five roads, with no loop, so each ceiling is met.

    why it is allowed: Lines 1 and 2 added.

  4. the move: it needs lists

    the line:
    lists of roads,not a grid\begin{gathered} \text{lists of roads,} \\ \text{not a grid} \end{gathered}

    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 nn 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.

  5. the move: read the bound

    the line:
    the whole method in O(n+m),in books, O(V+E)\begin{gathered} \text{the whole method in } O(n + m), \\ \text{in books, } O(V + E) \end{gathered}

    why it is allowed: 3n+2m3n + 2m is at most 3 times n+mn + m. 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 n+mn + m. A loop only stops the run sooner. On every pair, n+mn + m grows as the square of nn, as question 4's count does. In books VV is the places and EE the roads, not place E.

try it with a small mm: at m=5m = 5, line 1 gives N=10N = 10, which you can work out by hand

Question 6: why does every road run forwards? Let YY be how many do, on a map with no loop.
  1. the move: the far end waits

    the line:
    B joins only afterA to B is crossed off\begin{gathered} \text{B joins only after} \\ \text{A to B is crossed off} \end{gathered}

    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.

  2. the move: so the near end goes first

    the line:
    A is takenbefore B joins\begin{gathered} \text{A is taken} \\ \text{before B joins} \end{gathered}

    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.

  3. the move: numbers only grow

    the line:
    A’s number isbelow B’s\begin{gathered} \text{A's number is} \\ \text{below B's} \end{gathered}
    roadits start's numberits end's number
    A to B12
    A to E13
    B to C24
    B to F25
    E to F35
    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.

  4. the move: every road

    the line:
    Y=mY = m

    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 mm run forwards.

try it with a small mm: at m=5m = 5, line 4 gives Y=5Y = 5, 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.

A>B, A>E, B>E, every step written down
stepthe queue, front firstwhat happensroads crossed offplaces put in order
1AWrite at each of the 3 places how many roads come into it. Those with none, A, join the queue.A00
2A is at the front of the queue, so it takes number 1 in the order.01
3BCross off the road from A to B. No road is left coming into B, so it joins the back of the queue.B11
4BCross off the road from A to E: E still has one road coming in.B21
5B is at the front of the queue, so it takes number 2 in the order.22
6ECross off the road from B to E. No road is left coming into E, so it joins the back of the queue.E32
7E is at the front of the queue, so it takes number 3 in the order.33
8Done: every place is in order, 3 in all, and every road runs from a smaller number to a bigger one.33

In all, 3 roads crossed off. The formula from section 4, (n−1)+(n−2)+⋯+1+0(n - 1) + (n - 2) + \dots + 1 + 0, gives W=3W = 3 at n=3n = 3: 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 O(n+m)O(n + m) too.

methodtakes nexton a loopalso gives
this page's queuea place with no road left coming instops with places not takenlayers of places that can go at once
a deep walk read backwardsthe walk's next roadmeets a road back to a place not finished; the way from there to here, with that road, is the loopone order and no layers
On the small map the queue gives A, B, E, C, F, and the walk from A gives A, E, B, F, C. Both are right.
A1B3C5E2F4
From A, B, then C, which finishes. Back at B, F finishes, then B. Back at A, E finishes, as F is met already, then A. So C, F, B, E, A, and backwards A, E, B, F, C. Other numbers than the queue's, and every road still runs forwards.
ABECF
The small map in layers, a column each. A, then B and E, then C and F. Take everything in the queue together, and what that frees is the next layer. Each has nothing left to wait for, so they can go at once.