Skip to content

A* search

networks

Level 3 of 3

Also called A-star and Best-first search with a heuristic.

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.

1212101010ABCEF
Start at A, shaded, and reach C. Letters keep their spots on every map, A to D on top, E to H below, 10 a step. The lines left to C are A 20, B 10, E 23 and F 15.
201023ACE
Straight lines, not roads. E to C is 20 across and 10 up, so by Pythagoras the square root of 500, that is 400 + 100, about 22.4, rounded up to 23.
roundwaiting: so far + line leftsettleslooks alongwrites
1A 0 + 20A at 20A-B, A-EB 22, E 33
2B 12 + 10, E 10 + 23B at 22B-C, B-FC 24, F 37
3C 24 + 0, E 10 + 23, F 22 + 15C at 24none: C is the place to reachstop
The places waiting are those weighed up, 1 + 2 + 3, which is 6. E's road from A is shorter than B's, yet its estimate stays bigger. E and F are never settled. Dijkstra's method would settle all 5.
Along the top, the bottom never settled: 8 moments of its 11 steps, the steps between them left for the watch page
  1. step 1 of 11

    12101210101010141010A30BCDEFGH

    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.

    watch from here

  2. step 3 of 11

    12101210101010141010A30B32CDEFGH

    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

    watch from here

  3. step 4 of 11

    12101210101010141010A30B32CDE42FGH

    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

    watch from here

  4. step 5 of 11

    12101210101010141010A30B32CDE42FGH

    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

    watch from here

  5. step 6 of 11

    12101210101010141010A30B32C34DE42FGH

    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

    watch from here

  6. step 8 of 11

    12101210101010141010A30B32C34DE42F45GH

    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

    watch from here

  7. step 9 of 11

    12101210101010141010A30B32C34D38E42F45GH

    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

    watch from here

  8. step 11 of 11

    12101210101010141010A30B32C34D38E42F45G49H

    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

    watch from here

the steps, in plain words
  1. at the start, write the straight line from it to the place to reach as its estimatePython lines 39 and 42
  2. settle the place not settled yet with the smallest estimate: no way to it can be shorterPython lines 44, 45, 46 and 47
  3. look along each road from it to a place not settled yetPython lines 50, 51 and 52
  4. if the way through it is shorter, write that much so far plus the straight line leftPython lines 53, 54, 55, 56 and 57
  5. if not, keep the estimate therePython line 58
  6. 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
  7. 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. nn 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

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

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 along one straight row, each road as long as its straight line, from first letter to 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 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.

101010ABCD
A line of 4, from A to D. Settling a place writes an estimate only at the next, so one place waits in each round.
101010202030ABCD
Every pair of 4, each road as long as its straight line. Drawn bent so each road shows; really all 4 stand in one row, 10 apart.
rounda line of 4every pair of 4
111
213
312
411
all47
Places weighed up in each round. Settling A writes 30 at B, C and D, a tie, so they go in letter order, D last.

where the formula comes from

Each count above, line by line, then why the answer is right.

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.

  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}
    104015ABE
    Section 5's map, from A to E.
    place settledroads it looks alonghow manyskips
    AA-B, A-E20
    BB-E11
    Enone00
    all31
    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.

  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 a run that settles every place. 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. 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: why does a line of nn places, from one end, 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
    The line of 4 in section 3, from A to D.

    why it is allowed: KK 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 nn takes nn rounds.

  3. the move: add the ones

    the line:
    K=nK = n

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

  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, KK is at most 1 times nn, so the fixed multiple is 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 settling all 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=4n = 4, line 2 gives K=4K = 4, which you can work out by hand

Question 3: why does every pair in one row, first letter to 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
    placeroad from Aline leftestimate
    B102030
    C201030
    D30030
    Every pair of 4, as settling A writes them. Through B, C is still 20 and D still 30.

    why it is allowed: WW is the places weighed up. Round 1 weighs the start alone. It writes an estimate at the n−1n - 1 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.

  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. By question 1, that many looks too. 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. Two halves make n2n^2. 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, WW is at least a quarter of n2n^2, so the fixed multiple is 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: why does an estimate never fall as a way goes on?
  1. the move: a straight line is the shortest

    the line:
    the line left here is at mostthe line to the next placeplus the line left there\begin{gathered} \text{the line left here is at most} \\ \text{the line to the next place} \\ \text{plus the line left there} \end{gathered}
    101523EFC
    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.

  2. the move: a road is at least its line

    the line:
    a road is at leastits straight line\begin{gathered} \text{a road is at least} \\ \text{its straight line} \end{gathered}

    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.

  3. the move: the change along one road

    the line:
    Y=r+15−23Y = r + 15 - 23

    why it is allowed: YY is how much the estimate changes from E to F along a road of length rr. The way so far grows by rr. The line left goes from 23 to 15.

  4. the move: fifteen less twenty-three

    the line:
    Y=r−8Y = r - 8

    why it is allowed: 15 less 23 takes off 8. With rr at 10, YY is 2.

  5. the move: the road is at least 10

    the line:
    Y≥2Y \ge 2

    why it is allowed: By line 2, rr is at least 10, so YY is at least 2, above 0.

  6. the move: any road

    the line:
    along any road, an estimatestays or grows\begin{gathered} \text{along any road, an estimate} \\ \text{stays or grows} \end{gathered}

    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.

  7. the move: it never says too much

    the line:
    a line left is at mostany way on to the place to reach\begin{gathered} \text{a line left is at most} \\ \text{any way on to the place to reach} \end{gathered}

    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.

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

Question 5: why can no way beat a settled way?
  1. the move: every way so far is real

    the line:
    a way so far is the lengthof a real way\begin{gathered} \text{a way so far is the length} \\ \text{of a real way} \end{gathered}

    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.

  2. the move: suppose a shorter way

    the line:
    suppose a way shorter thanthe way so far being settled\begin{gathered} \text{suppose a way shorter than} \\ \text{the way so far being settled} \end{gathered}
    3512101010ABCEF
    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.

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

  4. the move: what x holds

    the line:
    x holds at most the way up to xplus its line left\begin{gathered} x \text{ holds at most the way up to } x \\ \text{plus its line left} \end{gathered}

    why it is allowed: The place before xx is settled with its shortest way, and it looked along the road to xx. So xx holds at most this way up to xx, plus its line left. Here, A's 0 plus 10, plus 23, so E holds 33.

  5. the move: the whole way's estimate

    the line:
    S=33+cS = 33 + c

    why it is allowed: SS 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 xx, then changes by cc along the rest. Here cc is 7.

  6. the move: an estimate never falls

    the line:
    S≥33S \ge 33

    why it is allowed: An estimate never falls, by question 4, so cc is at least 0. So on any map the estimate at the way's end is at least the one at xx. Here, 40 is at least 33.

  7. the move: x would come first

    the line:
    x has a smaller estimate thanthe place being settled\begin{gathered} x \text{ has a smaller estimate than} \\ \text{the place being settled} \end{gathered}

    why it is allowed: xx 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 xx first. Here, 33 is at most 40, and 40 is below 45, so E goes first.

  8. the move: so no shorter way

    the line:
    the way being settledis the shortest\begin{gathered} \text{the way being settled} \\ \text{is the shortest} \end{gathered}

    why it is allowed: Line 7 breaks the search's own rule, that the smallest estimate goes first (if xx 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.

  9. the move: round by round

    the line:
    each settled way is finaland the shortest\begin{gathered} \text{each settled way is final} \\ \text{and the shortest} \end{gathered}

    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.

try it with a small cc: at c=7c = 7, line 5 gives S=40S = 40, which you can work out by hand

Question 6: why must the line left never say too much?
  1. the move: a road shorter than its line

    the line:
    B to F is 2; itsstraight line is 10\begin{gathered} \text{B to F is 2; its} \\ \text{straight line is 10} \end{gathered}
    1121010ABEF
    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.

  2. the move: the real way looks worse

    the line:
    E is written 20, B 21,then F is written 20\begin{gathered} \text{E is written 20, B 21,} \\ \text{then F is written 20} \end{gathered}

    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.

  3. the move: the way through the short road

    the line:
    Z=11+rZ = 11 + r

    why it is allowed: ZZ is the way A, B, F. It is 11 up to B, then rr, the road left. Here rr is 2.

  4. the move: wrong, with no warning

    the line:
    it says 20;the shortest is 13\begin{gathered} \text{it says 20;} \\ \text{the shortest is 13} \end{gathered}

    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.

  5. the move: which line failed

    the line:
    an estimate fellfrom 21 to 13\begin{gathered} \text{an estimate fell} \\ \text{from 21 to 13} \end{gathered}

    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.

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

Question 7: why does A* settle no more places than Dijkstra's method, and does that make it cheaper?
  1. the move: the shortest way keeps a place waiting

    the line:
    a place of the shortest way waits,its estimate at most the answer\begin{gathered} \text{a place of the shortest way waits,} \\ \text{its estimate at most the answer} \end{gathered}

    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.

  2. the move: every place settled

    the line:
    a place settled has an estimateat most the answer\begin{gathered} \text{a place settled has an estimate} \\ \text{at most the answer} \end{gathered}

    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.

  3. the move: the most a way can be

    the line:
    T=38−dT = 38 - d

    why it is allowed: On the town of eight the answer is 38. By line 2, a settled place's way so far plus dd, its line left, is at most 38. So TT is the most its way can be. At C, dd is 10, so TT is 28, and C's way is 24.

  4. the move: before the end, every line left is at least 10

    the line:
    T≤28T \le 28

    why it is allowed: Every place but D stands at least one step from D, so dd is at least 10.

  5. the move: nearer than the answer

    the line:
    a place settled before the endis nearer than the answer\begin{gathered} \text{a place settled before the end} \\ \text{is nearer than the answer} \end{gathered}

    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.

  6. the move: no more places

    the line:
    Dijkstra’s methodsettles them too\begin{gathered} \text{Dijkstra's method} \\ \text{settles them too} \end{gathered}

    why it is allowed: It settles nearest first, so it settles every place nearer than the answer before it settles the place to reach.

  7. the move: a place written keeps waiting

    the line:
    a place written, never settled,waits every later round\begin{gathered} \text{a place written, never settled,} \\ \text{waits every later round} \end{gathered}
    10101010101010ABCDEFGH
    Side roads of 8, from A to D. E, F, G and H lead nowhere.
    roundA* waitingDijkstra's waiting
    1AA
    2B, EB, E
    3C, E, FC, E, F
    4D, E, F, GC, F
    5D, F, G
    6D, G
    weighed up1013
    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.

  8. the move: count each

    the line:
    a scan can weigh upfar more\begin{gathered} \text{a scan can weigh up} \\ \text{far more} \end{gathered}
    depth01232234421384349450321342423384435496457012
    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 methodsettled, looksweighed upwith a heap
    the town, A*4, 61014
    the town, Dijkstra's7, 91317
    side roads of 1,000, A*500, 998125,2508,478
    side roads of 1,000, Dijkstra's998, 9982,4932,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.

  9. the move: no more settled, not always cheaper

    the line:
    it settles no more,but it can cost more\begin{gathered} \text{it settles no more,} \\ \text{but it can cost more} \end{gathered}

    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.

try it with a small dd: at d=10d = 10, line 3 gives T=28T = 28, 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.

A-B 10, A-E 40, B-E 15; A E, every step written down
stepwhat happensroads looked alongplaces weighed up
1Start 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.00
2Of 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.01
3The 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.11
4The 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.21
5Of 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.23
6The 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.33
7E is settled at 25, 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

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.

methodpicks next byfindsneeds
A* searchthe smallest way so far plus line leftthe shortest way to one placeno road shorter than its straight line
Dijkstra's methodthe smallest way so farshortest ways from the startno length below 0
breadth-first searchthe place found longest ago, every road counting 1fewest roadsno lengths
On the town of eight below, the line left keeps the search off the bottom row.
12101210101010141010ABCDEFGH
A* settles the 4 shaded and says 38.
12101210101010141010ABCDEFGH
Dijkstra's method settles the 7 shaded and says 38.

race them on one row of your own