Dijkstra's 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.
| round | waiting | settles | looks along | writes |
|---|---|---|---|---|
| 1 | A 0 | A at 0 | A-B, A-E | B 9, E 2 |
| 2 | B 9, E 2 | E at 2 | E-F | F 4 |
| 3 | B 9, F 4 | F at 4 | F-B | B 6, beating 9 |
| 4 | B 6 | B at 6 | B-C | C 7 |
| 5 | C 7 | C at 7 | none: C is the place to reach | stop |
step 1 of 19
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.
step 4 of 19
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
step 8 of 19
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
step 10 of 19
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
step 11 of 19
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
step 13 of 19
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
step 18 of 19
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
step 19 of 19
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
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- write 0 at the start; no other place has a distance yetPython line 25
- settle the place not settled yet with the shortest distance: no way to it can be shorterPython lines 30, 31, 32 and 33
- look along each road from it to a place not settled yetPython lines 36, 37 and 38
- if the way through it is shorter, write the new distance therePython lines 39, 40, 41, 42 and 43
- if not, keep the distance therePython line 44
- 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
- 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. 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
, 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
| places weighed up | time | |
|---|---|---|
| 1,000 | 499,501 | about 500 microseconds |
| 100,000 | 4,999,950,001 | about 5 seconds |
| 10,000,000 | 49,999,995,000,001 | about 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.
| besta line, from one end to the other | worstevery pair joined, the place to reach settled last | |
|---|---|---|
| places weighed up | , one place waiting in each round | , all the rest waiting after round 1 |
| roads looked along | , each road once | , each road once |
| how the places weighed up grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
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.
| round | a line of 5 | every pair of 5 |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 4 |
| 3 | 1 | 3 |
| 4 | 1 | 2 |
| 5 | 1 | 1 |
| all | 5 | 11 |
where the formula comes from
Each count above, worked out line by line.
the move: each place settled once
the line: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.
the move: first end looks, second end skips
the line:place settled roads it looks along how many skips A A-B, A-E 2 0 E E-F 1 1 F F-B, F-G 2 1 B B-C 1 2 G G-C, G-H 2 1 C C-D 1 2 H H-D 1 1 D none 0 0 all 10 8 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.
guess it, thenthe move: one look for each road
the line:why it is allowed: is the roads looked along. By line 2 each of the roads gives one look.
guess it, thenthe move: add the ones
the line:why it is allowed: ones make . 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.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: a line's roads
the line:why it is allowed: The first place needs no road, and each place after it adds one. By question 1, looks.
the move: one place waits each round
the line:round waiting 1 A 2 B 3 C 4 D 5 H The line of 5 in section 3, from A to H. why it is allowed: 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 takes rounds.
guess it, thenthe move: add the ones
the line:why it is allowed: ones make . For 5 places, 5.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3, is , so it is at most .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:why it is allowed: By line 3, is , so it is at least .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple 1.
guess it, thenthe move: both together
the line:why it is allowed: Lines 5 and 7 bound by the same growth, .
guess it, thenthe move: no run weighs fewer
the line:why it is allowed: Each round weighs up the place it settles, so at least 1. A run that settles all has rounds, so it weighs up at least , which is by line 3.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: round by round
the line:round places waiting weighed up 1 A 1 2 B, C, D 3 3 C, D 2 4 D 1 all 7 4 places, every pair joined, every length 1, from A to D. why it is allowed: is the places weighed up. Round 1 weighs the start alone. It writes a distance at the others, so round 2 weighs them all. From then on each round settles one, so the next weighs one fewer.
the move: add up 1 to n - 1
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: is also how many roads every pair has: , in this line's fold. For 3 places, 3 times 2, halved, is 3, and 1 + 3 is 4.
guess it, thenthe move: open the bracket
the line:why it is allowed: times is .
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3. Its fraction is at most half of , and from 2 places on 1 is at most half of too. For 3, 4 is at most 9.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple 1.
guess it, thenthe move: drop the 1
the line:why it is allowed: A floor needs a fixed part of . Start from line 2, without its 1. For 3, 4 is at least 3.
guess it, thenthe move: halve n instead
the line:why it is allowed: The same product, with the halving on alone. For 3, 1.5 times 2 is 3.
guess it, thenthe move: n - 1 is at least half of n
the line:why it is allowed: From 2 places on, 1 is at most half of , so taking it from leaves at least half. For 3, 2 is at least 1.5.
guess it, thenthe move: multiply the halves
the line:why it is allowed: Half of times half of is a quarter of . For 3, 4 is at least 2.25.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 9, with the fixed multiple a quarter.
guess it, thenthe move: both together
the line: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 by the same growth, .
guess it, thenthe move: no run weighs more
the line:why it is allowed: Round 1 weighs only the start. By round 2 one place is settled, so at most can wait. By round 3 two are, so one fewer, and so on. Line 1 adds up exactly those.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: three counts
the line:every pair of 5 count places settled 5 places weighed up 11 roads looked along 10 the three together 26 26 is 5 times 5, plus 1. why it is allowed: adds the three with every pair joined. places settled, the places weighed up from question 3, and the looks, by question 1, every pair's roads by question 3's line 2.
the move: two halves make a whole
the line:why it is allowed: Two halves of make one. For 5, 5 + 1 + 20.
guess it, thenthe move: open the bracket
the line:why it is allowed: times is .
guess it, thenthe move: n and less n cancel
the line:why it is allowed: For 5, 26.
guess it, thenthe move: a ceiling
the line:why it is allowed: 1 is at most , so is at most . For 5, 26 is at most 50.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple 2.
guess it, thenthe move: any map
the line: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 .
guess it, thenthe move: a program's other reads
the line:why it is allowed: Each road is skipped once at most, by question 1's line 2, so at most . A program's scan can read every place each round, at most in all. Add line 7.
guess it, thenthe move: read the bound
the line:why it is allowed: Fixed multiple 4, as 1 is at most . By line 8, even a line of 5 can read 25.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: a heap replaces the scan
the line:round settles pushes the heap after, nearest first start none A0 A0 1 A0 B7, E2 E2, B7 2 E2 F4 F4, B7 3 F4 G7 B7, G7 4 B7 C14 G7, C14 5 G7 C9, H10 C9, H10, C14 6 C9 D13 H10, D13, C14 7 H10 D11 D11, D13, C14 8 D11 none D13, 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.
the move: count the pushes
the line:why it is allowed: is the most pushes. The start goes in once. By question 1 each of the roads is looked along once at most, and a look pushes at most one entry.
guess it, thenthe move: count the pops
the line:why it is allowed: Only what went in can come out.
guess it, thenthe move: each moves along one path
the line: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. entries height of entries 3 1 about 1.6 7 2 about 2.8 8 3 3 A heap's height never passes 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 entries, so it is at most levels high. A push climbs one path from the bottom, and a pop sinks one from the top.
guess it, thenthe move: pushes by places
the line:why it is allowed: By line 2, is one more than the roads, and no map has more roads than every pair. So is at most question 3's , and its line 4 puts at most . For the town, 11 is at most 64.
guess it, thenthe move: take logs of both sides
the line:why it is allowed: A bigger number has a bigger .
guess it, thenthe move: the log of a square
the line:why it is allowed: is times . doublings from 1 reach , and as many again reach .
guess it, thenthe move: pushes and pops together
the line:why it is allowed: At most pushes and pops, by lines 2 and 3.
guess it, thenthe move: levels in all
the line:why it is allowed: Each crosses at most levels, by lines 4 and 7. For the town, 4 times 11 times 3 is 132.
guess it, thenthe move: add settling and looks
the line:why it is allowed: Add places settled and looks.
guess it, thenthe move: replace the pushes
the line:why it is allowed: By line 2, is , and is at least 1, so is at most .
guess it, thenthe move: give the lone part a log
the line:why it is allowed: From 2 places on is at least 1.
guess it, thenthe move: add the two
the line:why it is allowed: 4 lots and one lot make 5. For the town, 5 times 18 times 3 is 270.
guess it, thenthe move: read the bound
the line:- the scan,
- 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 places the heap the scan a line 199 299 every pair, every length 1 5,451 10,001 every pair, every look finding a shorter way 34,770 10,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.
guess it, thenthe move: which way to lean
the line: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.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: every distance is a real way
the line: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.
the move: suppose a shorter way
the line: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.
guess it, thenthe move: its first place not settled
the line: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 is B.
guess it, thenthe move: x holds at most that much
the line:why it is allowed: The place before is settled, its distance right, so no longer than this way up to it. It looked along the road to , so holds at most the way up to . Here, A's 0 plus 9, so B holds 9.
guess it, thenthe move: the whole way
the line:why it is allowed: is the whole way A, B, F. It is 9 up to , then more, the rest of the way. Here is 2.
guess it, thenthe move: the rest is at least 0
the line:why it is allowed: Going on from only adds lengths, and no length is below 0, so is at least 0. So on any map the whole way is at least the way up to . Here, 11 is at least 9.
guess it, thenthe move: x would come first
the line:why it is allowed: holds at most the way up to , 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 first.
guess it, thenthe move: so no shorter way
the line: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.
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
the move: a length below 0
the line:The shortest way to B, drawn heavy, A, C, E, B. one-way road length A to B 6 A to C 7 C to E 3 E to B A to B alone is 6. A, C, E, B is 7 plus 3 plus , 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.
the move: the nearer place settled first
the line: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.
guess it, thenthe move: the way round
the line:why it is allowed: is the way A, C, E, B. It is 7 up to C, then less, what the rest of the way takes off. Here is 2, as C to E adds 3 and E to B takes off 5.
guess it, thenthe move: wrong, with no warning
the line: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.
guess it, thenthe move: which line failed
the line:why it is allowed: Line 6 of question 6 says the whole way is at least the way up to . Here is C. The way up to C is 7, and the whole way is 5.
guess it, then
try it with a small : at , line 3 gives , 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.
| step | what happens | roads looked along | places weighed up |
|---|---|---|---|
| 1 | Start at A, 0 from itself, and find the shortest way to E. No other place has a distance yet. | 0 | 0 |
| 2 | Of 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. | 0 | 1 |
| 3 | The 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. | 1 | 1 |
| 4 | The 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. | 2 | 1 |
| 5 | Of 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. | 2 | 3 |
| 6 | The 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. | 3 | 3 |
| 7 | E is settled at 3, so the shortest way is found: A, B and E. | 3 | 4 |
In all, 4 places weighed up. The formula from section 4, , gives at : 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
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.
| method | picks next by | finds | lengths below 0 |
|---|---|---|---|
| Dijkstra's method | the shortest whole way from the start | shortest ways from the start | no |
| breadth-first search | the place found longest ago, every road counting 1 | fewest roads | uses no lengths |
| Prim's method | the shortest single road to it | a cheapest network | yes |