Skip to content

Dijkstra's shortest paths

networks

Level 2 of 3

Also called Dijkstra's algorithm and Single-source shortest paths.

how it works

The idea on a small map, then one run on the town of eight, from A to D.

Dijkstra's method finds the shortest way from one place to another along roads with lengths, none below 0. A place's distance is the shortest way found to it from the start so far. Write 0 at the start. Then repeat. Of the places waiting, those with a distance and not settled yet, settle the nearest to the start, the one with the smallest number. Its distance is now final. Two equally near go in letter order. Look along each of its roads to a place not settled yet. If that place has no distance, or the way through is shorter, write the new one, and note the road it came by. Stop once the place to reach is settled. The noted roads lead back to the start. The watch page finds the nearest by a scan: each round it weighs up every place waiting. This page counts those, so a place that waits three rounds counts three times. The Python below finds the nearest with a heap instead, which section 4's question 5 explains.

92221ABCEF
A shorter way found late. Start at A, shaded, and reach C. Along the top, A to B alone is 9.
roundwaitingsettleslooks alongwrites
1A 0A at 0A-B, A-EB 9, E 2
2B 9, E 2E at 2E-FF 4
3B 9, F 4F at 4F-BB 6, beating 9
4B 6B at 6B-CC 7
5C 7C at 7none: C is the place to reachstop
The places waiting are those weighed up, 1 + 2 + 2 + 1 + 1, which is 7. B holds 9 for two rounds, then 6.
92221A0B6C7E2F4
Each place shows its letter, then its final distance. Drawn heavy, the shortest way, 7.
Round the bottom beats along the top: 8 moments of its 19 steps, the steps between them left for the watch page
  1. step 1 of 19

    7272332431A0BCDEFGH

    Start at A, 0 from itself, and find the shortest way to D. No other place has a distance yet.

    what it remembers to know where it is
    settled last
    not yet
    its distance
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 4 of 19

    7272332431A0B7CDE2FGH

    The road from A to E is 2 long, so through A it is 2 to E, shorter than any way found before. Write 2 at E.

    what it remembers to know where it is
    settled last
    A
    its distance
    0

    watch from here

  3. step 8 of 19

    7272332431A0B7CDE2F4GH

    The road from F to B is 3 long, so through F it is 7 to B, no shorter than the 7 written there. Keep 7.

    what it remembers to know where it is
    settled last
    F
    its distance
    4

    watch from here

  4. step 10 of 19

    7272332431A0B7CDE2F4G7H

    Of the places with a distance and not settled yet, B is the nearest, at 7. Settle it: any other way to B would go through a place at least as far away.

    what it remembers to know where it is
    settled last
    B
    its distance
    7

    watch from here

  5. step 11 of 19

    7272332431A0B7C14DE2F4G7H

    The road from B to C is 7 long, so through B it is 14 to C, shorter than any way found before. Write 14 at C.

    what it remembers to know where it is
    settled last
    B
    its distance
    7

    watch from here

  6. step 13 of 19

    7272332431A0B7C9DE2F4G7H

    The road from G to C is 2 long, so through G it is 9 to C, shorter than any way found before. Write 9 at C.

    what it remembers to know where it is
    settled last
    G
    its distance
    7

    watch from here

  7. step 18 of 19

    7272332431A0B7C9D11E2F4G7H10

    The road from H to D is 1 long, so through H it is 11 to D, shorter than any way found before. Write 11 at D.

    what it remembers to know where it is
    settled last
    H
    its distance
    10

    watch from here

  8. step 19 of 19

    7272332431A0B7C9D11E2F4G7H10

    D is settled at 11, so the shortest way is found: A, E, F, G, H and D.

    what it remembers to know where it is
    settled last
    D
    its distance
    11

    watch from here

the steps, in plain words
  1. write 0 at the start; no other place has a distance yetPython line 25
  2. settle the place not settled yet with the shortest distance: no way to it can be shorterPython lines 30, 31, 32 and 33
  3. look along each road from it to a place not settled yetPython lines 36, 37 and 38
  4. if the way through it is shorter, write the new distance therePython lines 39, 40, 41, 42 and 43
  5. if not, keep the distance therePython line 44
  6. once the place to reach is settled, the roads back to the start are the shortest wayPython lines 34, 35, 53, 54, 55, 56 and 57
  7. if no place left has a distance, the place to reach cannot be reachedPython lines 29, 51 and 52
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 heapq import heappop, heappush


def dijkstra(roads, start, end):
    """Find the shortest way from start to end along roads with lengths.

    roads is a list of (place, place, length), each road running both
    ways, no length below 0. It stops once end is settled. Returns the
    distance written at each place by then: end's is the answer, if it
    has one. A place with no distance is left out.
    """
    return search(neighbours(roads), start, end)[0]


def neighbours(roads):
    """Each place's roads, as pairs of the place at the far end and the length."""
    near = {}
    for a, b, length in roads:  # a road runs both ways
        near.setdefault(a, []).append((b, length))
        near.setdefault(b, []).append((a, length))
    return near


def search(near, start, end):
    distance = {start: 0}  # write 0 at the start
    came_from = {}  # the place each distance came through
    settled = set()
    heap = [(0, start)]  # entries of distance and place, nearest on top
    while heap:  # none left: end cannot be reached
        _, here = heappop(heap)  # the nearest; on a tie, first in letter order
        if here in settled:  # an old entry: a shorter one came first
            continue
        settled.add(here)  # settle it: no way to it can be shorter
        if here == end:  # end is settled, so its way is found
            break
        for there, length in near.get(here, []):  # each road from it
            if there in settled:  # only to a place not settled yet
                continue
            total = distance[here] + length  # the way through here
            if there not in distance or total < distance[there]:  # shorter?
                distance[there] = total  # write the new distance there
                came_from[there] = here
                heappush(heap, (total, there))
            # if not, keep the distance there
    return distance, came_from


def shortest_route(roads, start, end):
    """The places on a shortest way from start to end, or None if no way."""
    distance, came_from = search(neighbours(roads), start, end)
    if end not in distance:  # no place left had a distance, and end had none
        return None
    route = [end]
    while route[-1] != start:  # the roads back to the start
        route.append(came_from[route[-1]])
    route.reverse()
    return route

how it scales

How many places the search weighs up on a line, from one end to the other, and on every pair joined, each run settling every place. nn on the plot is how many places, 10 to 1,000.

Each mark across or up is ten times the one before. A line climbs one mark up for each mark across: 100 at 100 places and 1,000 at 1,000. Every pair joined climbs two marks up for each: 4,951 at 100 places and 499,501 at 1,000.

places weighed up, 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 joined, the place to reach settled lastsolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
  • a line, from one end to the othersolid where measured by running it; dashed where its formula carries it on to ten million
what every pair joined costs, at a billion places weighed up a second
nnplaces weighed uptime
1,000499,501about 500 microseconds
100,0004,999,950,001about 5 seconds
10,000,00049,999,995,000,001about 14 hours

The places weighed up 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 Dijkstra's places weighed up 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, from the first place to the last, every length 1: a line, the
fewest roads that join them, and every two places joined, the most. It
prints the places weighed up for each, by count below, the search with a
scan in place of the heap. The counts are the same on any computer; only
the time differs.
"""
from heapq import heappop, heappush


def dijkstra(roads, start, end):
    """Find the shortest way from start to end along roads with lengths.

    roads is a list of (place, place, length), each road running both
    ways, no length below 0. It stops once end is settled. Returns the
    distance written at each place by then: end's is the answer, if it
    has one. A place with no distance is left out.
    """
    return search(neighbours(roads), start, end)[0]


def neighbours(roads):
    """Each place's roads, as pairs of the place at the far end and the length."""
    near = {}
    for a, b, length in roads:  # a road runs both ways
        near.setdefault(a, []).append((b, length))
        near.setdefault(b, []).append((a, length))
    return near


def search(near, start, end):
    distance = {start: 0}  # write 0 at the start
    came_from = {}  # the place each distance came through
    settled = set()
    heap = [(0, start)]  # entries of distance and place, nearest on top
    while heap:  # none left: end cannot be reached
        _, here = heappop(heap)  # the nearest; on a tie, first in letter order
        if here in settled:  # an old entry: a shorter one came first
            continue
        settled.add(here)  # settle it: no way to it can be shorter
        if here == end:  # end is settled, so its way is found
            break
        for there, length in near.get(here, []):  # each road from it
            if there in settled:  # only to a place not settled yet
                continue
            total = distance[here] + length  # the way through here
            if there not in distance or total < distance[there]:  # shorter?
                distance[there] = total  # write the new distance there
                came_from[there] = here
                heappush(heap, (total, there))
            # if not, keep the distance there
    return distance, came_from


def shortest_route(roads, start, end):
    """The places on a shortest way from start to end, or None if no way."""
    distance, came_from = search(neighbours(roads), start, end)
    if end not in distance:  # no place left had a distance, and end had none
        return None
    route = [end]
    while route[-1] != start:  # the roads back to the start
        route.append(came_from[route[-1]])
    route.reverse()
    return route


def count(roads, start, end):
    """How many places a scan weighs up: the search above with no heap,
    looking over every place with a distance and not settled yet."""
    near = neighbours(roads)
    distance = {start: 0}
    settled = set()
    weighed = 0
    while True:
        waiting = [place for place in distance if place not in settled]
        if not waiting:
            return weighed
        weighed += len(waiting)
        here = min(waiting, key=lambda place: (distance[place], place))
        settled.add(here)
        if here == end:
            return weighed
        for there, length in near.get(here, []):
            if there not in settled:
                total = distance[here] + length
                if there not in distance or total < distance[there]:
                    distance[there] = total


def line(n):
    """n places in a line, p0001 onward, each road 1 long: n - 1 roads."""
    return [(f"p{k:04}", f"p{k + 1:04}", 1) for k in range(1, n)]


def every_pair(n):
    """n places, every two joined, each road 1 long: n(n - 1) / 2 roads."""
    return [(f"p{a:04}", f"p{b:04}", 1) 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]:
        first, last = "p0001", f"p{n:04}"
        print(f"{n:>6} {count(line(n), first, last):>8} {count(every_pair(n), first, last):>12}")

best, worst and average

This section's runs settle every place: the map is in one piece, and the place to reach comes last. A run that reaches it sooner stops sooner. Each round weighs up the places waiting, and this page's count is how many wait. With 8 places, a line weighs up 8, the town of eight 14, and every pair 29.

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 line, from one end to the otherworstevery pair joined, the place to reach settled last
places weighed upnn, one place waiting in each round1+n(n−1)21 + \frac{n(n - 1)}{2}, all the rest waiting after round 1
roads looked alongn−1n - 1, each road oncen(n−1)2\frac{n(n - 1)}{2}, each road once
how the places weighed up 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 distance, the road it came by and a settled mark at each place. With a heap, at most one entry for the start and one for each road too.

Extra memory is the room it needs on top of the input itself, while it runs.

1111ABCDH
A line of 5 places, from A to H. Settling a place writes a distance only at the next, so one place waits in each round.
ABCDE
Every pair joined, every length 1, from A to E. Settling A writes 1 at all 4 others, so they all wait. Tied at 1, they go in letter order, so E comes last.
rounda line of 5every pair of 5
111
214
313
412
511
all511
Places weighed up in each round. With every pair, after round 1 every place has a distance, so each round settles one and none joins.

where the formula comes from

Each count above, worked out line by line.

Question 1: when a run settles every place, why does it look along each road once, mm roads in all?
  1. the move: each place settled once

    the line:
    each place issettled once\begin{gathered} \text{each place is} \\ \text{settled once} \end{gathered}

    why it is allowed: Only places not settled yet are weighed up, so a place settled is never settled again. This run settles them all.

  2. the move: first end looks, second end skips

    the line:
    a road is looked alongfrom its end settled first\begin{gathered} \text{a road is looked along} \\ \text{from its end settled first} \end{gathered}
    place settledroads it looks alonghow manyskips
    AA-B, A-E20
    EE-F11
    FF-B, F-G21
    BB-C12
    GG-C, G-H21
    CC-D12
    HH-D11
    Dnone00
    all108
    The town of eight from A to D, in the order settled. D stops the run.

    why it is allowed: When one end is settled, the other is not settled yet, so the road is looked along. When the other end is settled later, the road leads to a settled place, so it is skipped.

  3. the move: one look for each road

    the line:
    L=1+1+⋯+1L = 1 + 1 + \dots + 1

    why it is allowed: LL is the roads looked along. By line 2 each of the mm roads gives one look.

  4. the move: add the ones

    the line:
    L=mL = m

    why it is allowed: mm ones make mm. For the town of eight, 10 roads, 10 looks. Each place keeps a list of its roads, so a road's second end reads it too, to skip it. This page counts looks, not skips.

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

Question 2: from one end, why does a line of nn places weigh up only nn, the fewest when every place is settled?
  1. the move: a line's roads

    the line:
    a line of n places:n−1 roads\begin{gathered} \text{a line of } n \text{ places:} \\ n - 1 \text{ roads} \end{gathered}

    why it is allowed: The first place needs no road, and each place after it adds one. By question 1, n−1n - 1 looks.

  2. the move: one place waits each round

    the line:
    K=1+1+⋯+1K = 1 + 1 + \dots + 1
    roundwaiting
    1A
    2B
    3C
    4D
    5H
    The line of 5 in section 3, from A to H.

    why it is allowed: KK is the places weighed up. From one end, settling a place writes a distance only at the next, so one place waits in each round. Settling all nn takes nn rounds.

  3. the move: add the ones

    the line:
    K=nK = n

    why it is allowed: nn ones make nn. For 5 places, 5.

  4. the move: a ceiling

    the line:
    K≤nK \le n

    why it is allowed: By line 3, KK is nn, so it is at most nn.

  5. the move: read the bound

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

    why it is allowed: By line 4, with the fixed multiple 1.

  6. the move: a floor

    the line:
    K≥nK \ge n

    why it is allowed: By line 3, KK is nn, so it is at least nn.

  7. the move: read the bound

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

    why it is allowed: By line 6, with the fixed multiple 1.

  8. the move: both together

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

    why it is allowed: Lines 5 and 7 bound KK by the same growth, nn.

  9. the move: no run weighs fewer

    the line:
    n rounds, eachweighing at least 1\begin{gathered} n \text{ rounds, each} \\ \text{weighing at least } 1 \end{gathered}

    why it is allowed: Each round weighs up the place it settles, so at least 1. A run that settles all nn has nn rounds, so it weighs up at least nn, which is KK by line 3.

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

Question 3: why does a map with every pair joined, the place to reach settled last, weigh up 1+n(n−1)21 + \frac{n(n - 1)}{2}, the most?
  1. the move: round by round

    the line:
    W=1+(n−1)+⋯+2+1W = 1 + (n - 1) + \dots + 2 + 1
    roundplaces waitingweighed up
    1A1
    2B, C, D3
    3C, D2
    4D1
    all7
    4 places, every pair joined, every length 1, from A to D.

    why it is allowed: WW is the places weighed up. Round 1 weighs the start alone. It writes a distance at the n−1n - 1 others, so round 2 weighs them all. From then on each round settles one, so the next weighs one fewer.

  2. the move: add up 1 to n - 1

    the line:
    W=1+n(n−1)2W = 1 + \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: (n−1)+⋯+2+1(n - 1) + \dots + 2 + 1 is also how many roads every pair has: n(n−1)2\frac{n(n - 1)}{2}, in this line's fold. For 3 places, 3 times 2, halved, is 3, and 1 + 3 is 4.

  3. the move: open the bracket

    the line:
    W=1+n2−n2W = 1 + \frac{n^2 - n}{2}

    why it is allowed: nn times n−1n - 1 is n2−nn^2 - n.

  4. the move: a ceiling

    the line:
    W≤n2W \le n^2

    why it is allowed: By line 3. Its fraction is at most half of n2n^2, and from 2 places on 1 is at most half of n2n^2 too. For 3, 4 is at most 9.

  5. the move: read the bound

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

    why it is allowed: By line 4, with the fixed multiple 1.

  6. the move: drop the 1

    the line:
    W≥n(n−1)2W \ge \frac{n(n - 1)}{2}

    why it is allowed: A floor needs a fixed part of n2n^2. Start from line 2, without its 1. For 3, 4 is at least 3.

  7. the move: halve n instead

    the line:
    W≥n2(n−1)W \ge \frac{n}{2}(n - 1)

    why it is allowed: The same product, with the halving on nn alone. For 3, 1.5 times 2 is 3.

  8. the move: n - 1 is at least half of n

    the line:
    W≥n2×n2W \ge \frac{n}{2} \times \frac{n}{2}

    why it is allowed: From 2 places on, 1 is at most half of nn, so taking it from nn leaves at least half. For 3, 2 is at least 1.5.

  9. the move: multiply the halves

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

    why it is allowed: Half of nn times half of nn is a quarter of n2n^2. For 3, 4 is at least 2.25.

  10. the move: read the bound

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

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

  11. the move: both together

    the line:
    W∈Θ(n2)W \in \Theta(n^2)
    places weighed upplaces0204060801000246810places weighed upplaces0204060801000246810
    • n2n^2
    • WW
    • n24\frac{n^2}{4}
    WW stays between its floor and its ceiling. At 10 places, 25 is at most 46, and 46 is at most 100.

    why it is allowed: Lines 5 and 10 bound WW by the same growth, n2n^2.

  12. the move: no run weighs more

    the line:
    any map of n places:at most W weighed up\begin{gathered} \text{any map of } n \text{ places:} \\ \text{at most } W \text{ weighed up} \end{gathered}

    why it is allowed: Round 1 weighs only the start. By round 2 one place is settled, so at most n−1n - 1 can wait. By round 3 two are, so one fewer, and so on. Line 1 adds up exactly those.

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

Question 4: with a scan, why do places settled, places weighed up and looks come to at most n2+1n^2 + 1?
  1. the move: three counts

    the line:
    T=n+(1+n(n−1)2)+n(n−1)2\begin{gathered} T = n + \left(1 + \frac{n(n - 1)}{2}\right) \\ + \frac{n(n - 1)}{2} \end{gathered}
    every pair of 5count
    places settled5
    places weighed up11
    roads looked along10
    the three together26
    26 is 5 times 5, plus 1.

    why it is allowed: TT adds the three with every pair joined. nn places settled, the places weighed up from question 3, and the looks, mm by question 1, every pair's roads by question 3's line 2.

  2. the move: two halves make a whole

    the line:
    T=n+1+n(n−1)T = n + 1 + n(n - 1)

    why it is allowed: Two halves of n(n−1)n(n - 1) make one. For 5, 5 + 1 + 20.

  3. the move: open the bracket

    the line:
    T=n+1+n2−nT = n + 1 + n^2 - n

    why it is allowed: nn times n−1n - 1 is n2−nn^2 - n.

  4. the move: n and less n cancel

    the line:
    T=n2+1T = n^2 + 1

    why it is allowed: For 5, 26.

  5. the move: a ceiling

    the line:
    T≤2n2T \le 2n^2

    why it is allowed: 1 is at most n2n^2, so n2+1n^2 + 1 is at most 2n22n^2. For 5, 26 is at most 50.

  6. the move: read the bound

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

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

  7. the move: any map

    the line:
    any map: those threeat most n2+1\begin{gathered} \text{any map: those three} \\ \text{at most } n^2 + 1 \end{gathered}

    why it is allowed: By question 3's last line, no run weighs up more. No map has more roads, by that question's line 2, and no run settles more than nn.

  8. the move: a program's other reads

    the line:
    other reads too:at most 3n2+1\begin{gathered} \text{other reads too:} \\ \text{at most } 3n^2 + 1 \end{gathered}

    why it is allowed: Each road is skipped once at most, by question 1's line 2, so at most n2n^2. A program's scan can read every place each round, at most n2n^2 in all. Add line 7.

  9. the move: read the bound

    the line:
    still O(n2),in books, O(V2)\begin{gathered} \text{still } O(n^2), \\ \text{in books, } O(V^2) \end{gathered}

    why it is allowed: Fixed multiple 4, as 1 is at most n2n^2. By line 8, even a line of 5 can read 25.

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

Question 5: with a heap, why do levels moved, places settled and looks grow no faster than (n+m) log⁡2 n(n + m) \,\log_2\, n?
  1. the move: a heap replaces the scan

    the line:
    the heap keepsthe nearest on top\begin{gathered} \text{the heap keeps} \\ \text{the nearest on top} \end{gathered}
    roundsettlespushesthe heap after, nearest first
    startnoneA0A0
    1A0B7, E2E2, B7
    2E2F4F4, B7
    3F4G7B7, G7
    4B7C14G7, C14
    5G7C9, H10C9, H10, C14
    6C9D13H10, D13, C14
    7H10D11D11, D13, C14
    8D11noneD13, C14
    The town of eight from A to D. E2 means E at distance 2. C14 and D13 are old entries, beaten by C9 and D11.

    why it is allowed: Each new distance goes in the heap as an entry, a push. To settle, the top entry comes out, a pop. An old entry is passed by when it comes up.

  2. the move: count the pushes

    the line:
    J=1+mJ = 1 + m

    why it is allowed: JJ is the most pushes. The start goes in once. By question 1 each of the mm roads is looked along once at most, and a look pushes at most one entry.

  3. the move: count the pops

    the line:
    at most Jpops\begin{gathered} \text{at most } J \\ \text{pops} \end{gathered}

    why it is allowed: Only what went in can come out.

  4. the move: each moves along one path

    the line:
    each at mostlog⁡2 J levels\begin{gathered} \text{each at most} \\ \log_2\, J \text{ levels} \end{gathered}
    depth012224719141013021427394145106137012
    A heap of 7 entries, its height 2. Each entry is no bigger than those below it. A push into the last spot climbs the path marked.
    entriesheightlog⁡2\log_2 of entries
    31about 1.6
    72about 2.8
    833
    A heap's height never passes log⁡2\log_2 of its entries.

    why it is allowed: A heap fills each level before the next, 1 entry, then 2, then 4. By line 2 it holds at most JJ entries, so it is at most log⁡2 J\log_2\, J levels high. A push climbs one path from the bottom, and a pop sinks one from the top.

  5. the move: pushes by places

    the line:
    J is at most n2J \text{ is at most } n^2

    why it is allowed: By line 2, JJ is one more than the roads, and no map has more roads than every pair. So JJ is at most question 3's WW, and its line 4 puts WW at most n2n^2. For the town, 11 is at most 64.

  6. the move: take logs of both sides

    the line:
    log⁡2 J is at most  log⁡2 n2\log_2\, J \text{ is at most } \,\log_2\, n^2

    why it is allowed: A bigger number has a bigger log⁡2\log_2.

  7. the move: the log of a square

    the line:
    log⁡2 J is at most 2 log⁡2 n\log_2\, J \text{ is at most } 2 \,\log_2\, n

    why it is allowed: n2n^2 is nn times nn. log⁡2 n\log_2\, n doublings from 1 reach nn, and as many again reach n2n^2.

  8. the move: pushes and pops together

    the line:
    at most 2Jmoves\begin{gathered} \text{at most } 2J \\ \text{moves} \end{gathered}

    why it is allowed: At most JJ pushes and JJ pops, by lines 2 and 3.

  9. the move: levels in all

    the line:
    at most4J log⁡2 n levels\begin{gathered} \text{at most} \\ 4J \,\log_2\, n \text{ levels} \end{gathered}

    why it is allowed: Each crosses at most 2 log⁡2 n2 \,\log_2\, n levels, by lines 4 and 7. For the town, 4 times 11 times 3 is 132.

  10. the move: add settling and looks

    the line:
    at most4J log⁡2 n+n+m\begin{gathered} \text{at most} \\ 4J \,\log_2\, n + n + m \end{gathered}

    why it is allowed: Add nn places settled and mm looks.

  11. the move: replace the pushes

    the line:
    at most4(n+m) log⁡2 n+n+m\begin{gathered} \text{at most} \\ 4(n + m) \,\log_2\, n + n + m \end{gathered}

    why it is allowed: By line 2, JJ is 1+m1 + m, and nn is at least 1, so JJ is at most n+mn + m.

  12. the move: give the lone part a log

    the line:
    at most4(n+m) log⁡2 n+(n+m) log⁡2 n\begin{gathered} \text{at most} \\ 4(n + m) \,\log_2\, n + (n + m) \,\log_2\, n \end{gathered}

    why it is allowed: From 2 places on log⁡2 n\log_2\, n is at least 1.

  13. the move: add the two

    the line:
    at most5(n+m) log⁡2 n\begin{gathered} \text{at most} \\ 5(n + m) \,\log_2\, n \end{gathered}

    why it is allowed: 4 lots and one lot make 5. For the town, 5 times 18 times 3 is 270.

  14. the move: read the bound

    the line:
    levels, settling and looks inO((n+m) log⁡2 n)in books, O((V+E) log⁡2 V)\begin{gathered} \text{levels, settling and looks in} \\ O((n + m) \,\log_2\, n) \\ \text{in books, } O((V + E) \,\log_2\, V) \end{gathered}
    10210410610810101012101410161011021031041051061071011021031041051061071081091010101110121013101410151016101102103104105106107
    • the scan, n2n^2
    • the heap, 3 roads a place
    • the heap, every pair joined
    The ceilings' growth, fixed multiples left out. With few roads the heap's grows far slower than the scan's. With every pair joined it grows faster.
    a map of 100 placesthe heapthe scan
    a line199299
    every pair, every length 15,45110,001
    every pair, every look finding a shorter way34,77010,001
    Counted by running each. Both count places settled and looks, the heap also levels moved, the scan also places weighed up. In the third, with places in a row, a road is 1, plus 2 for each place it jumps. A heap is not always quicker.

    why it is allowed: By line 13, with the fixed multiple 5, from 2 places on. Skips, and a push or pop that moves no level, change only the multiple.

  15. the move: which way to lean

    the line:
    few roads: the heap’sceiling grows slower;every pair: the scan’s\begin{gathered} \text{few roads: the heap's} \\ \text{ceiling grows slower;} \\ \text{every pair: the scan's} \end{gathered}

    why it is allowed: By line 14's plot, as maps grow. A ceiling says the most a run can cost, not what it does cost, as that line's table shows.

try it with a small mm: at m=10m = 10, line 2 gives J=11J = 11, which you can work out by hand

Question 6: why can no way beat a settled distance?
  1. the move: every distance is a real way

    the line:
    a distance written isthe length of a real way\begin{gathered} \text{a distance written is} \\ \text{the length of a real way} \end{gathered}

    why it is allowed: The start's 0 is the way of no roads. Any other distance is a settled place's distance plus one road's length, so it is a real way too.

  2. the move: suppose a shorter way

    the line:
    suppose a way shorter thanthe distance being settled\begin{gathered} \text{suppose a way shorter than} \\ \text{the distance being settled} \end{gathered}
    92221ABCEF
    Round 3 of the small map at the top. A and E are settled, and F is nearest at 4. Another way to F is drawn heavy, A, B, F. At 11 it is not shorter, only an example. Its first place not settled is B.

    why it is allowed: Say the search is about to settle a place after the start, and every place settled so far has its right distance. Suppose some way to this place is shorter. Follow it from the start.

  3. the move: its first place not settled

    the line:
    call its first placenot settled x\begin{gathered} \text{call its first place} \\ \text{not settled } x \end{gathered}

    why it is allowed: The way starts at a settled place and ends at one not settled, so some place is first. In the picture xx is B.

  4. the move: x holds at most that much

    the line:
    x holds at most theway up to x\begin{gathered} x \text{ holds at most the} \\ \text{way up to } x \end{gathered}

    why it is allowed: The place before xx is settled, its distance right, so no longer than this way up to it. It looked along the road to xx, so xx holds at most the way up to xx. Here, A's 0 plus 9, so B holds 9.

  5. the move: the whole way

    the line:
    S=9+rS = 9 + r

    why it is allowed: SS is the whole way A, B, F. It is 9 up to xx, then rr more, the rest of the way. Here rr is 2.

  6. the move: the rest is at least 0

    the line:
    S≥9S \ge 9

    why it is allowed: Going on from xx only adds lengths, and no length is below 0, so rr is at least 0. So on any map the whole way is at least the way up to xx. Here, 11 is at least 9.

  7. the move: x would come first

    the line:
    x is nearer than theplace being settled\begin{gathered} x \text{ is nearer than the} \\ \text{place being settled} \end{gathered}

    why it is allowed: xx holds at most the way up to xx, by line 4. That is at most the whole way, by line 6. Line 2 supposed the whole way is below this place's distance. So the search would settle xx first.

  8. the move: so no shorter way

    the line:
    each settled distanceis final and right\begin{gathered} \text{each settled distance} \\ \text{is final and right} \end{gathered}

    why it is allowed: Line 7 breaks the search's own rule, so no way is shorter. By line 1 the distance is a real way, so it is right. A settled place is never written again, so it is final. The start's 0 is right, as no way adds up below 0, so each round in turn settles a right distance.

try it with a small rr: at r=2r = 2, line 5 gives S=11S = 11, which you can work out by hand

Question 7: why does one length below 0 break it?
  1. the move: a length below 0

    the line:
    one way:E to B is −5\begin{gathered} \text{one way:} \\ E \text{ to } B \text{ is } -5 \end{gathered}
    ABCE
    The shortest way to B, drawn heavy, A, C, E, B.
    one-way roadlength
    A to B6
    A to C7
    C to E3
    E to B−5-5
    A to B alone is 6. A, C, E, B is 7 plus 3 plus −5-5, which is 5.

    why it is allowed: These roads run one way. On a two-way road below 0 you could go back and forth, shorter each time, so no way would be shortest.

  2. the move: the nearer place settled first

    the line:
    B is settled at 6\begin{gathered} B \text{ is settled at } 6 \end{gathered}

    why it is allowed: Search from A to B. Settling A writes B 6 and C 7. B is nearer, so round 2 settles it at 6, and the run stops.

  3. the move: the way round

    the line:
    Z=7−rZ = 7 - r

    why it is allowed: ZZ is the way A, C, E, B. It is 7 up to C, then rr less, what the rest of the way takes off. Here rr is 2, as C to E adds 3 and E to B takes off 5.

  4. the move: wrong, with no warning

    the line:
    it says 6;the shortest is 5\begin{gathered} \text{it says } 6; \\ \text{the shortest is } 5 \end{gathered}

    why it is allowed: By lines 2 and 3. Running on past B would not help, as a settled place gets no new distance. The answer looks like any other, and nothing says it is wrong.

  5. the move: which line failed

    the line:
    a way got shorterby going on\begin{gathered} \text{a way got shorter} \\ \text{by going on} \end{gathered}

    why it is allowed: Line 6 of question 6 says the whole way is at least the way up to xx. Here xx is C. The way up to C is 7, and the whole way is 5.

try it with a small rr: at r=2r = 2, line 3 gives Z=5Z = 5, which you can work out by hand

count it yourself

Count every place weighed up and every road looked along on every pair of 3 places: A, B and E. On the watch page you type this map as A-B 2, A-E 5, B-E 1; A E. After the semicolon, A is the start and E the place to reach. E is first written 5, then beaten, and is settled at 3. The last two columns are running totals.

A-B 2, A-E 5, B-E 1; A E, every step written down
stepwhat happensroads looked alongplaces weighed up
1Start at A, 0 from itself, and find the shortest way to E. No other place has a distance yet.00
2Of the places with a distance and not settled yet, A is the nearest, at 0. Settle it: any other way to A would go through a place at least as far away.01
3The road from A to B is 2 long, so through A it is 2 to B, shorter than any way found before. Write 2 at B.11
4The road from A to E is 5 long, so through A it is 5 to E, shorter than any way found before. Write 5 at E.21
5Of the places with a distance and not settled yet, B is the nearest, at 2. Settle it: any other way to B would go through a place at least as far away.23
6The road from B to E is 1 long, so through B it is 3 to E, shorter than any way found before. Write 3 at E.33
7E is settled at 3, so the shortest way is found: A, B and E.34

In all, 4 places weighed up. The formula from section 4, 1+n(n−1)21 + \frac{n(n - 1)}{2}, gives W=4W = 4 at n=3n = 3: the same.

where you meet it

Routers, machines that pass traffic across a network, use this search. A widely used Python library gives it to you ready made.

  • OSPF, inside large networks

    OSPF is a set of rules routers follow to pass traffic inside a large network, which can be split into areas. A map of an area, a cost on each link, is copied to every router in it. A router starts this search at itself, and the links that gave each distance make its tree of shortest routes.

    source: the Internet Engineering Task Force's RFC 2328 (opens in a new tab), sections 1.1, 3 and 16.1

  • networkx's shortest paths

    networkx, a library for building and studying networks of things, keeps the waiting places in a heap, as this page's Python does. If a length below 0 gives a settled place a shorter way, it stops with an error.

    source: the networkx source, weighted.py (opens in a new tab), its _dijkstra_multisource

7223231ABCDEFGH
The town of eight's tree of shortest routes from A, the road that gave each place its distance. 7 roads for 8 places, with no loop. Start elsewhere and the tree changes.

what is used instead

When every road counts 1, use breadth-first search, which writes the same numbers and needs no heap. When a one-way road can be below 0, this search can be wrong, by section 4's question 7. Use Bellman-Ford, which goes over every road again and again. If a loop on the way adds up below 0, no way is shortest. For one far place on a huge map, A* adds a guess of the way left, never too long, so the search leans toward it.

how it compares

These three repeat the same steps, and differ in how they pick what comes next.

methodpicks next byfindslengths below 0
Dijkstra's methodthe shortest whole way from the startshortest ways from the startno
breadth-first searchthe place found longest ago, every road counting 1fewest roadsuses no lengths
Prim's methodthe shortest single road to ita cheapest networkyes
On the maps below, with A and B done, Prim's compares single roads to E, B-E 1 against A-E 2, and takes B-E. Dijkstra's compares whole ways, 2 + 1 against 2, and keeps A-E.
221ABE
Shortest ways from A, drawn heavy, 2 to B and 2 to E. Their roads add up to 4.
221ABE
One of this map's two cheapest networks, drawn heavy, adding up to 3. The other is A-E and B-E. But A to E along the heavy roads is 3, not 2. Each picture is best at its own job.

race them on one row of your own