Find the shortest path

In the reel, a wave checked 109 squares and A* checked 29. Both found the same 16-step path. Here's how a good guess saves 80 squares without ever getting the answer wrong.

The reel's map, run live: squares checked by each search. Tap to play it again. Further down, you paint your own walls.

1Why did A* check 80 fewer squares?

Same map, same start, same goal. One search checked 109 squares. The other checked 29. Both found a path of 16 steps.

A still from the one-minute reel: f = g + h above a grid map, with the counters 109 for the wave and 29 for A*

A still from the one-minute reel.

The map is a grid of squares, 15 across and 9 down. S is the start and G is the goal. A wall stands in the middle with a way round at the top.

You may move up, down, left or right, one square at a time. Each move is one step. A shortest path is a route from S to G with the fewest steps.

To "check" a square, the search stops there and asks two things. Is this the goal? If not, which of its neighbours haven't I seen yet? Each check is one bit of work, so fewer checks means a faster answer.

Both searches give the same answer. The puzzle is why one needs so much less work.

2Race them yourself

Press Run. Then paint some walls and run it again. Can you make A* check more squares than the wave?

The wave0 checked

A*0 checked

wallchecked by the wavechecked by A*path found

Drag on either map to paint or erase walls (not on S or G). Both maps share the walls. The numbers on squares: on the wave, steps from S. On A*, a total that section 5 explains.

Try the map called "Goal walled in". Neither search finds a path, and both check all 126 squares they can reach first. A search can only say "no way through" after it has run out of places to look.

A* checks fewer squares on most maps, but it never gives a longer path.

3How the wave works

It's like dropping a stone in a pond. The ripple reaches near things first, then far things.

Every blue square shows its number of steps from S. The yellow line is the 16-step path. The empty squares on the right were never checked.

Work it out the way the wave does. Write 0 in S. Its 4 neighbours are 1 step away. Their new neighbours are 2 steps away, and so on. The wave checks all the 1s, then all the 2s, then all the 3s.

So when it first reaches G, nothing nearer is left unchecked. That's why its path is always a shortest one.

Now count. There are 105 squares less than 16 steps from S, and the wave checks every one of them. There are 8 squares exactly 16 steps away. The wave checks 4 of them, and the 4th is G. 105 + 4 = 109.

Most of that work points the wrong way. The wave checks the whole left side, behind S, even though G is on the right. A real ripple stops being a good picture here: water fades as it spreads, but the wave keeps going at full strength until it finds G.

The real name is breadth-first search, or BFS: check everything 1 step away, then everything 2 steps away, and so on.

The wave is always right, but it checks every square nearer than the goal, in every direction.

4A cheap guess of the distance

You already know roughly where G is. Can you use that without risking a wrong answer?

Tap any square. The dashed teal line is the guess: across, then up or down, straight through the wall. The yellow squares are the real shortest way to G.

Here's the guess, worked out for S by hand. S is in column 1 and G is in column 13, so they're 12 columns apart. They're in the same row, so 0 rows apart. The guess is 12 + 0 = 12.

The true distance from S is 16. The wall forces 2 steps up and 2 steps back down, and the guess didn't know about the wall. So the guess was 4 too small.

It's like counting city blocks to a friend's house. You count the blocks across and the blocks up, and you add them. If a road is closed, the real walk gets longer. A closed road can never make it shorter.

That last point is the important one. Every step moves you one column or one row. So you need at least as many steps as the guess, and walls can only add more. On this map the guess is exactly right for 87 of the 129 open squares. It's never too big for any of them.

A guess like this is called a heuristic: a quick estimate that's good enough to steer by. This one is the Manhattan distance, named after walking Manhattan's grid of streets. A guess that is never bigger than the truth is called admissible.

When the guess breaks

If you could also move diagonally, one diagonal step would cover a column and a row at once. The guess would count 2 for it, but it costs 1. The guess could then be too big, and A* could miss the shortest path. This page uses up, down, left and right only.

The guess ignores walls, so it can be too small, but it is never too big.

5Add the two: f = g + h

The wave only asks how far it has come. A* also asks how far is probably left.

One square, by hand

Take the square just above the end of the straight line, row 3, column 6. (Rows and columns are counted from 0, top left.)

  1. Steps so far: from S, walk 5 steps right and 1 step up. That's 6.
  2. The guess from here: G is 7 columns across and 1 row down, so 7 + 1 = 8.
  3. Add them: 6 + 8 = 14. That's A*'s estimate of the whole trip if it goes through this square.

A* keeps a list of squares it has seen but not checked. It always checks the one with the smallest total next. If two tie, it picks the one with the smaller guess. It's like a hiker at a fork who adds the distance already walked to what the signpost says is left. The comparison breaks if a signpost says the walk is longer than it really is. That's why the guess must never be too big.

Why it checks 29

Every square A* checked shows its total, steps so far plus the guess. The yellow squares are the path. Three bands: 12, 14 and 16.

A step towards G adds 1 to the steps and takes 1 off the guess. The total stays the same. A step away from G adds 1 to both, so the total goes up by 2.

  1. From S straight towards the wall, the total stays at 12. A* checks those 6 squares first.
  2. At the wall, no square with total 12 is left. Squares one step off the line have total 14. A* checks all 13 of them, looking for a way round.
  3. The way round goes 2 steps up the wall, away from G. That's 12 + 2 + 2 = 16. Over the top and down to G, the total stays 16. That's 10 squares, and the last is G.

6 + 13 + 10 = 29. The total at G is 16 + 0 = 16: 16 steps taken, nothing left to guess. That's the reel's last line.

Why it never misses the shortest path. Every square on a 16-step path has a total of at most 16, because the guess is never too big. A square with a total above 16 can't be on a shortest path, so A* can skip it safely. On this map 52 squares have a total of 16 or less. A* checked 29 of them, because ties go to the square closer to G.

The real name is A*, said "A star". It's breadth-first search with the guess added. The symbols: g is the steps so far, h is the guess of steps left, and f is the total.

The formula

f = g + h
h = |columns apart| + |rows apart|

How much does it save?

MapWave checkedA* checkedSharePath (steps)
Open room1021313 %12
Wall with a gap (the reel)1092927 %16
Dead-end slot1154035 %18
Rooms765066 %20

The surprise is the open room. With no walls the guess is exact everywhere, so A* checks only the 13 squares of its own 12-step path. It doesn't waste a single check. The more walls block the straight line, the less the guess helps. These are small maps drawn for this page, so treat the shares as examples.

A common mistake: "just aim at the goal"

It sounds smart to ignore the steps so far and just head for whichever square looks closest to G. On the rooms map that checks 41 squares instead of A*'s 50. But it finds a 30-step path, when the shortest is 20. That's 10 steps longer, or 50 % more.

Aiming only at the goal walks into dead ends and long ways round. Adding g is what keeps A* honest: a route that has already cost a lot stops looking cheap.

Where it's used. Video game characters that walk round walls, and route planners on real maps, use ideas like this. On a road map the squares become junctions, the steps become travel times, and the guess still must never be too big.

A* checks the square with the smallest steps-so-far plus guess, so it skips squares that can't be on a shortest path.

6Write the wave yourself

About 40 lines of Python. Then you turn it into A*.

This is the wave on a small map, counting the squares it checks. Save it as bfs.py and run python bfs.py.

from collections import deque

grid = ["S..#....",
        ".#.#.##.",
        ".#...#..",
        ".####.#.",
        "......#G"]

def find(ch):
    for r, row in enumerate(grid):
        if ch in row:
            return (r, row.index(ch))

def bfs(start, goal):
    queue = deque([start])
    came_from = {start: None}
    looked_at = 0
    while queue:
        cell = queue.popleft()
        looked_at += 1
        if cell == goal:
            break
        r, c = cell
        for nr, nc in [(r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)]:
            if (0 <= nr < len(grid) and 0 <= nc < len(grid[0])
                    and grid[nr][nc] != "#" and (nr, nc) not in came_from):
                came_from[(nr, nc)] = cell
                queue.append((nr, nc))
    if goal not in came_from:
        return looked_at, None
    steps = 0
    cell = goal
    while came_from[cell] is not None:
        cell = came_from[cell]
        steps += 1
    return looked_at, steps

print(bfs(find("S"), find("G")))

Expected output:

(27, 15)

It checked 27 squares and found a path of 15 steps. The guess from S to G is 11, so the walls cost 4 extra steps. The queue is the waiting line: squares join at the back and get checked from the front, which is what makes it a wave. came_from remembers how each square was reached, so you can walk the path back from G.

Build: three changes

Change the code, and check your answers with the race in section 2.

  • Wall in the goal: put a # at row 3, column 7 (the last . of the fourth row). You should get (25, None): it checked all 25 squares it could reach, then gave up.
  • Print the path itself, not just its length, by following came_from back from the goal.
  • Turn it into A*: keep the steps so far for each square, and always check the square with the smallest steps-so-far plus guess.

Show it with: your code, its output, and a sentence on what you learned.

Go deeper (optional)

A queue of squares to check is the whole wave. Sort that list by f = g + h and it becomes A*.

Recap

  1. The wave (breadth-first search) checks squares in order of steps from the start, so its first path to G is a shortest one.
  2. On the reel's map that costs 109 checks: all 105 squares nearer than 16 steps, plus 4 at 16.
  3. The Manhattan guess counts columns plus rows. Walls can only make the real trip longer, so it's never too big.
  4. A* checks the smallest f = g + h next. It skips squares that can't be on a shortest path: 29 checks, same 16 steps.

Build your first robot

HalfSmart, a 3D-printed 5-axis robot arm, is coming to Jig Pro as a full step-by-step build. Join the waitlist and we'll tell you when it opens.

Join the waitlist