A* search
how it works
The idea on a small map, then one run on the town of eight, from A to D.
A* search finds the shortest way from one place to another, as Dijkstra's method does, but it leans toward the place to reach. Each place holds an estimate: its way so far, plus its line left, the straight line from it to the place to reach. That line is a guess at the way still to go. No road is shorter than the straight line between its ends, and going by other places cannot beat a straight line. So the line left never says too much: it is never more than the way still to go. Write the start's estimate. A place with an estimate, not settled yet, is waiting. Now repeat, round by round. Settle the waiting place with the smallest estimate. Two equal go in letter order. Look along each of its roads to a place not settled yet. If that place has no estimate, or the way through the place just settled is shorter, write the new one, and note the road. Stop once the place to reach is settled. Its line left is 0, so its estimate is the way itself. The watch page finds the smallest by a scan: each round it weighs up every place waiting. This page counts those. The Python below uses a heap instead.
| round | waiting: so far + line left | settles | looks along | writes |
|---|---|---|---|---|
| 1 | A 0 + 20 | A at 20 | A-B, A-E | B 22, E 33 |
| 2 | B 12 + 10, E 10 + 23 | B at 22 | B-C, B-F | C 24, F 37 |
| 3 | C 24 + 0, E 10 + 23, F 22 + 15 | C at 24 | none: C is the place to reach | stop |
step 1 of 11
Start at A, 0 from itself. The straight line to D is 30, and no way can be shorter than that, so write 30 as the estimate at A.
what it remembers to know where it is
- settled last
- not yet
- distance so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 3 of 11
The road from A to B is 12 long, so B is 12 so far, plus a straight line of 20 still to go: 32 in all, the best yet. Write 32 at B.
what it remembers to know where it is
- settled last
- A
- distance so far
- 0
step 4 of 11
The road from A to E is 10 long, so E is 10 so far, plus a straight line of 32 still to go: 42 in all, the best yet. Write 42 at E.
what it remembers to know where it is
- settled last
- A
- distance so far
- 0
step 5 of 11
Of the places with an estimate and not settled yet, B has the smallest, 32. Settle it: the way to it, 12, cannot be made shorter.
what it remembers to know where it is
- settled last
- B
- distance so far
- 12
step 6 of 11
The road from B to C is 12 long, so C is 24 so far, plus a straight line of 10 still to go: 34 in all, the best yet. Write 34 at C.
what it remembers to know where it is
- settled last
- B
- distance so far
- 12
step 8 of 11
Of the places with an estimate and not settled yet, C has the smallest, 34. Settle it: the way to it, 24, cannot be made shorter.
what it remembers to know where it is
- settled last
- C
- distance so far
- 24
step 9 of 11
The road from C to D is 14 long, so D is 38 so far, plus a straight line of 0 still to go: 38 in all, the best yet. Write 38 at D.
what it remembers to know where it is
- settled last
- C
- distance so far
- 24
step 11 of 11
D is settled at 38, so the shortest way is found: A, B, C and D.
what it remembers to know where it is
- settled last
- D
- distance so far
- 38
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- at the start, write the straight line from it to the place to reach as its estimatePython lines 39 and 42
- settle the place not settled yet with the smallest estimate: no way to it can be shorterPython lines 44, 45, 46 and 47
- look along each road from it to a place not settled yetPython lines 50, 51 and 52
- if the way through it is shorter, write that much so far plus the straight line leftPython lines 53, 54, 55, 56 and 57
- if not, keep the estimate therePython line 58
- once the place to reach is settled, the roads back to the start are the shortest wayPython lines 48, 49, 67, 68, 69, 70 and 71
- if no place left has an estimate, the place to reach cannot be reachedPython lines 43, 65 and 66
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
from math import ceil, hypot
def a_star(roads, start, end):
"""Find the shortest way from start to end, leaning toward end.
roads is a list of (place, place, length), each road running both
ways, none shorter than the straight line between its ends. It stops
once end is settled. Returns the estimate written at each place by
then: end's is the answer, if it has one. A place with no estimate
is left out.
"""
sofar, _ = search(neighbours(roads), start, end)
return {place: way + straight(place, end) for place, way in sofar.items()}
def spot(place):
"""Where a place stands: its row and column, A to D above, E to H below."""
return divmod("ABCDEFGH".index(place), 4)
def straight(a, b):
"""The straight line between two places, 10 a step, rounded up."""
(row_a, col_a), (row_b, col_b) = spot(a), spot(b)
return ceil(10 * hypot(row_a - row_b, col_a - col_b))
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):
sofar = {start: 0} # the way to each place so far
came_from = {} # the place each way came through
settled = set()
heap = [(straight(start, end), start)] # estimate and place, smallest on top
while heap: # none left: end cannot be reached
_, here = heappop(heap) # the smallest; on a tie, first in letter order
if here in settled: # an old entry: a smaller 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 = sofar[here] + length # the way through here
if there not in sofar or total < sofar[there]: # shorter?
sofar[there] = total # that much so far, plus the line left
came_from[there] = here
heappush(heap, (total + straight(there, end), there))
# if not, keep the estimate there
return sofar, came_from
def shortest_route(roads, start, end):
"""The places on a shortest way from start to end, or None if no way."""
sofar, came_from = search(neighbours(roads), start, end)
if end not in sofar: # no place left had an estimate, 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
The plot counts places weighed up on two maps, each run settling every place. One is places in a line, each joined to the next, from first to last. The other is every pair joined along one straight row, from first letter to last. on the plot 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: 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 along one straight row, each road as long as its straight line, from first letter to 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 A*'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, 10 apart in one straight row, from the first place to the last: a
line, the fewest roads that join them, and every two places joined, each
road as long as its straight line, 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
from math import ceil, hypot
def a_star(roads, start, end):
"""Find the shortest way from start to end, leaning toward end.
roads is a list of (place, place, length), each road running both
ways, none shorter than the straight line between its ends. It stops
once end is settled. Returns the estimate written at each place by
then: end's is the answer, if it has one. A place with no estimate
is left out.
"""
sofar, _ = search(neighbours(roads), start, end)
return {place: way + straight(place, end) for place, way in sofar.items()}
def spot(place):
"""Where a place stands: its row and column, A to D above, E to H below."""
return divmod("ABCDEFGH".index(place), 4)
def straight(a, b):
"""The straight line between two places, 10 a step, rounded up."""
(row_a, col_a), (row_b, col_b) = spot(a), spot(b)
return ceil(10 * hypot(row_a - row_b, col_a - col_b))
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):
sofar = {start: 0} # the way to each place so far
came_from = {} # the place each way came through
settled = set()
heap = [(straight(start, end), start)] # estimate and place, smallest on top
while heap: # none left: end cannot be reached
_, here = heappop(heap) # the smallest; on a tie, first in letter order
if here in settled: # an old entry: a smaller 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 = sofar[here] + length # the way through here
if there not in sofar or total < sofar[there]: # shorter?
sofar[there] = total # that much so far, plus the line left
came_from[there] = here
heappush(heap, (total + straight(there, end), there))
# if not, keep the estimate there
return sofar, came_from
def shortest_route(roads, start, end):
"""The places on a shortest way from start to end, or None if no way."""
sofar, came_from = search(neighbours(roads), start, end)
if end not in sofar: # no place left had an estimate, 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 stands(place):
"""As spot, and past the letters: p0001 onward along one straight row."""
return (0, int(place[1:])) if place.startswith("p") else spot(place)
def guess(a, b):
"""The straight line between any two places, as straight does for letters."""
(row_a, col_a), (row_b, col_b) = stands(a), stands(b)
return ceil(10 * hypot(row_a - row_b, col_a - col_b))
def count(roads, start, end):
"""How many places a scan weighs up: the search above with no heap,
looking over every place with an estimate and not settled yet."""
near = neighbours(roads)
sofar = {start: 0}
left = {start: guess(start, end)}
settled = set()
weighed = 0
while True:
waiting = [place for place in sofar if place not in settled]
if not waiting:
return weighed
weighed += len(waiting)
here = min(waiting, key=lambda place: (sofar[place] + left[place], place))
settled.add(here)
if here == end:
return weighed
for there, length in near.get(here, []):
if there not in settled:
total = sofar[here] + length
if there not in sofar or total < sofar[there]:
sofar[there] = total
left[there] = guess(there, end)
def line(n):
"""n places in a line, p0001 onward, each road 10 long: n - 1 roads."""
return [(f"p{k:04}", f"p{k + 1:04}", 10) for k in range(1, n)]
def every_pair(n):
"""n places, every two joined, each road its straight line: n(n - 1) / 2 roads."""
return [(f"p{a:04}", f"p{b:04}", 10 * (b - a)) 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
A run can stop early: on the town of eight, it settles 4 of its 8 places and weighs up 10. So this section takes only runs that settle every place, with the place to reach last: there the line left saves nothing. The average is not worked out here.
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 along one straight row, each road as long as its straight line, from first letter to 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 way so far, an estimate, the road it came by and a settled mark at each place. With a heap, one entry for the start and at most one for each road, by question 1.
Extra memory is the room it needs on top of the input itself, while it runs.
| round | a line of 4 | every pair of 4 |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 3 |
| 3 | 1 | 2 |
| 4 | 1 | 1 |
| all | 4 | 7 |
where the formula comes from
Each count above, line by line, then why the answer is right.
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.
the move: first end looks, second end skips
the line:Section 5's map, from A to E. place settled roads it looks along how many skips A A-B, A-E 2 0 B B-E 1 1 E none 0 0 all 3 1 In the order settled; E stops the run. All 3 roads are looked along, each once. 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 a run that settles every place. 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 . 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 The line of 4 in section 3, from A to D. why it is allowed: is the places weighed up. Settling a place writes an estimate only at the next, so one place waits in each round, whatever its estimate. Settling all takes rounds.
guess it, thenthe move: add the ones
the line:why it is allowed: ones make . For 4 places, 4.
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, is at most 1 times , so the fixed multiple is 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 settling all 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:place road from A line left estimate B 10 20 30 C 20 10 30 D 30 0 30 Every pair of 4, as settling A writes them. Through B, C is still 20 and D still 30. why it is allowed: is the places weighed up. Round 1 weighs the start alone. It writes an estimate at the others, all tied, so round 2 weighs them all. No way through another place is shorter, so they stay tied. Letter order settles one each round, the far end last, so each next round 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. By question 1, that many looks too. 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. Two halves make . 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, is at least a quarter of , so the fixed multiple is 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: a straight line is the shortest
the line:Straight lines on the small map, not its roads. 23 is at most 10 + 15. why it is allowed: Going by way of another place cannot beat the straight line. So the line left at E, 23, is at most E to F, 10, plus the line left at F, 15. Rounded up, it still holds. 10 + 15 is a whole number, at least 22.4, so at least 23.
the move: a road is at least its line
the line:why it is allowed: The watch page's box for typing a map refuses a road any shorter. E-F is 10, and its straight line is 10.
guess it, thenthe move: the change along one road
the line:why it is allowed: is how much the estimate changes from E to F along a road of length . The way so far grows by . The line left goes from 23 to 15.
guess it, thenthe move: fifteen less twenty-three
the line:why it is allowed: 15 less 23 takes off 8. With at 10, is 2.
guess it, thenthe move: the road is at least 10
the line:why it is allowed: By line 2, is at least 10, so is at least 2, above 0.
guess it, thenthe move: any road
the line:why it is allowed: On any road, the line left falls by at most the road's straight line, by line 1. The road adds at least that, by line 2. So the change is at least 0.
guess it, thenthe move: it never says too much
the line:why it is allowed: Count any way from 0. Along E, F, B, C, 10 + 10 + 12, the estimate starts 0 + 23, ends 32 + 0. By line 6, 23 is at most 32.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: every way so far is real
the line:why it is allowed: The start's 0 is the way of no roads. Any other is a settled place's way so far plus one road's length, so it is a real way too.
the move: suppose a shorter way
the line:The small map with A-B made 35. A is settled. Say B, holding 35 + 10, which is 45, were about to be settled. Drawn heavy, a shorter way to B, 30. Its first place not settled is E. why it is allowed: Say the search is about to settle a place after the start, and every place settled so far has its shortest way. Suppose some way to this place is shorter. Following it breaks the search's own rule, so no such way exists.
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 E.
guess it, thenthe move: what x holds
the line:why it is allowed: The place before is settled with its shortest way, and it looked along the road to . So holds at most this way up to , plus its line left. Here, A's 0 plus 10, plus 23, so E holds 33.
guess it, thenthe move: the whole way's estimate
the line:why it is allowed: is the estimate this way gives at its end, the way's length, 30, plus B's line left, 10, so 40. It is 33 at , then changes by along the rest. Here is 7.
guess it, thenthe move: an estimate never falls
the line:why it is allowed: An estimate never falls, by question 4, so is at least 0. So on any map the estimate at the way's end is at least the one at . Here, 40 is at least 33.
guess it, thenthe move: x would come first
the line:why it is allowed: holds at most the way's estimate, by lines 4 and 6. Line 2 supposed this way is shorter than the place's way so far, and both end with the same line left. So the search would settle first. Here, 33 is at most 40, and 40 is below 45, so E goes first.
guess it, thenthe move: so no shorter way
the line:why it is allowed: Line 7 breaks the search's own rule, that the smallest estimate goes first (if is that place, it is below itself), so no way is shorter. By line 1 the way so far is real, so it is the shortest.
guess it, thenthe move: round by round
the line:why it is allowed: The start's 0 is the shortest, as no way adds up below 0. So each round in turn has what line 2 asks, and settles a shortest way. A settled place is never written again.
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
the move: a road shorter than its line
the line:From A to F. Drawn heavy, the shortest way. The lines left to F are A 15, B 10 and E 10. why it is allowed: The watch page's box refuses this road, and this map shows why. At B the line left says 10, when only 2 is left. So it says too much.
the move: the real way looks worse
the line:why it is allowed: Settling A writes E 10 + 10 and B 11 + 10. E is smaller, so it is settled next, and it writes F 20 + 0.
guess it, thenthe move: the way through the short road
the line:why it is allowed: is the way A, B, F. It is 11 up to B, then , the road left. Here is 2.
guess it, thenthe move: wrong, with no warning
the line:why it is allowed: F's 20 is below B's 21, so F is settled, and the run stops. By line 3, the way through B is 13. 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: Going on from B to F, the estimate falls by 8, against question 4. Question 5's line 6 needs it never to fall.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: the shortest way keeps a place waiting
the line:why it is allowed: Until the place to reach is settled, the shortest way to it has a first place not settled, as in question 5. By that question's lines 4 and 6, its estimate is at most the estimate at the way's end, the answer. On the town, after A, B waits at 32, and the answer is 38.
the move: every place settled
the line:why it is allowed: The search settles the smallest estimate, so no bigger than that waiting place's. On the town, A 30, B 32, C 34, D 38.
guess it, thenthe move: the most a way can be
the line:why it is allowed: On the town of eight the answer is 38. By line 2, a settled place's way so far plus , its line left, is at most 38. So is the most its way can be. At C, is 10, so is 28, and C's way is 24.
guess it, thenthe move: before the end, every line left is at least 10
the line:why it is allowed: Every place but D stands at least one step from D, so is at least 10.
guess it, thenthe move: nearer than the answer
the line:why it is allowed: On any map with an answer, its line left is above 0, so by line 2 its way is below it. By question 5 that way is the shortest.
guess it, thenthe move: no more places
the line:why it is allowed: It settles nearest first, so it settles every place nearer than the answer before it settles the place to reach.
guess it, thenthe move: a place written keeps waiting
the line:Side roads of 8, from A to D. E, F, G and H lead nowhere. round A* waiting Dijkstra's waiting 1 A A 2 B, E B, E 3 C, E, F C, E, F 4 D, E, F, G C, F 5 D, F, G 6 D, G weighed up 10 13 A* leaves E, F and G waiting, so its list grows each round. Dijkstra's method settles E and F. On side roads of 1,000, A*'s list grows to 500, and 1 + 2 up to 500 is 125,250. why it is allowed: A scan weighs it up each of those rounds, so settling no more need not mean cheaper.
guess it, thenthe move: count each
the line:A heap of 7 entries, smallest on top. A new entry goes in last and climbs the path marked while smaller than the one above, one level a step. map and method settled, looks weighed up with a heap the town, A* 4, 6 10 14 the town, Dijkstra's 7, 9 13 17 side roads of 1,000, A* 500, 998 125,250 8,478 side roads of 1,000, Dijkstra's 998, 998 2,493 2,494 Counted by running each, roads in letter order. The last column adds places settled, looks and levels moved in a heap. why it is allowed: On side roads of 1,000, A* settles about half as many places but weighs up about 50 times as many.
guess it, thenthe move: no more settled, not always cheaper
the line:why it is allowed: A heap has no scan, yet a longer heap moves more levels, so A* costs more on side roads too. It saves looks when the places it leaves alone have roads of their own, as on the town.
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, drawn in section 4's question 1. On the watch page you type this map as A-B 10, A-E 40, B-E 15; A E. After the semicolon, A is the start and E the place to reach. E is first written 40, then beaten, and is settled at 25. These 3 stand in no row, yet the rounds still weigh up 1, 2 and 1, as question 3 adds them. The last two columns are running totals.
| step | what happens | roads looked along | places weighed up |
|---|---|---|---|
| 1 | Start at A, 0 from itself. The straight line to E is 10, and no way can be shorter than that, so write 10 as the estimate at A. | 0 | 0 |
| 2 | Of the places with an estimate and not settled yet, A has the smallest, 10. Settle it: the way to it, 0, cannot be made shorter. | 0 | 1 |
| 3 | The road from A to B is 10 long, so B is 10 so far, plus a straight line of 15 still to go: 25 in all, the best yet. Write 25 at B. | 1 | 1 |
| 4 | The road from A to E is 40 long, so E is 40 so far, plus a straight line of 0 still to go: 40 in all, the best yet. Write 40 at E. | 2 | 1 |
| 5 | Of the places with an estimate and not settled yet, B has the smallest, 25. Settle it: the way to it, 10, cannot be made shorter. | 2 | 3 |
| 6 | The road from B to E is 15 long, so E is 25 so far, plus a straight line of 0 still to go: 25 in all, the best yet. Write 25 at E. | 3 | 3 |
| 7 | E is settled at 25, 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
A 1968 paper set it out, and ready-made Python code gives it to you.
Hart, Nilsson and Raphael's paper
Three researchers at the Stanford Research Institute wrote it: Peter Hart, Nils Nilsson and Bertram Raphael. Their search may settle a place again, and they prove that a guess that never says too much still finds the shortest way. This page's search settles a place once, so it needs question 4: an estimate never falls. Hart recalls the work as a way to navigate the institute's robot, Shakey.
source: the paper, A Formal Basis for the Heuristic Determination of Minimum Cost Paths (opens in a new tab), and the Computer History Museum's oral history of Peter Hart (opens in a new tab), page 30
networkx's astar_path
networkx, ready-made Python code that works on maps of places and roads, gives this search as astar_path. You hand it your own guess, and it keeps the waiting places in a heap, as this page's Python does. Its help warns that the way it gives can be longer than the shortest if your guess says too much.
source: the networkx source, astar.py (opens in a new tab), its astar_path
what is used instead
When you want the shortest way to every place, use Dijkstra's method: an estimate aims at one place only. When you have no fair guess, write a line left of 0 everywhere, and this search is Dijkstra's method.
how it compares
These three repeat the same steps, and differ in how they pick what comes next.
| method | picks next by | finds | needs |
|---|---|---|---|
| A* search | the smallest way so far plus line left | the shortest way to one place | no road shorter than its straight line |
| Dijkstra's method | the smallest way so far | shortest ways from the start | no length below 0 |
| breadth-first search | the place found longest ago, every road counting 1 | fewest roads | no lengths |