Algorithms · Maps & places
A* search
**A*: how a map app finds your route without trying them all.** Search toward where you’re going, not in every direction at once.
The problem
You type "home" into a map app and want directions to a place far away. The road network is a huge web of intersections joined by road segments. Somewhere in that web is the quickest route, and you expect it in a blink.
Navigation software builds on shortest-path search. The trouble is scale: a continent has an enormous number of intersections, and millions of people ask for routes all the time. Checking every possible route is hopeless.
The obvious way
The classic answer is Dijkstra's algorithm. It always expands the closest unexplored place next, so it spreads out like a ripple in a pond, evenly in every direction. It is correct, but it has no sense of direction. If you're heading east, it still carefully explores west, north and south, until the ripple finally reaches your goal.
The clever idea
Imagine walking through a city toward a tower you can see on the skyline. You don't check every street equally. You favor the streets that point at the tower. That is A\* (Hart, Nilsson and Raphael, 1968): Dijkstra plus a guess about how far is left.
Each place is ranked by distance already traveled plus a heuristic, a cheap estimate of the distance remaining. On a grid, the Manhattan distance (steps across plus steps down) works well. Places that look closer to the goal get explored first, so the search leans toward the goal instead of rippling everywhere.
How the code does it
Both searches run the same function, search. The heuristic on this line is the only thing that changes: Manhattan distance for A*, or a flat 0 for Dijkstra. Each cell is pushed onto the priority queue on line 21 with a score of cost so far + guess, and the pop always takes the lowest score.
With a guess of 0, cells are ranked only by distance traveled, so the search ripples outward. With Manhattan distance, cells nearer the goal rank better, so the search streams toward it. Walking the parent links backward rebuilds the path, and the last lines draw both runs and chart how many cells each one visited. Blue is everything it looked at, orange is the final route.
Trade-offs
A* is only as good as its guess. The estimate must never be bigger than the true remaining distance, or it can miss the shortest route. If the guess is useless (like 0), you're back to Dijkstra. Real roads are also far bigger than this grid, so production navigation systems add heavy precomputation, such as contraction hierarchies, to answer continent-scale queries fast. I'm not claiming anything about Google Maps' internals, only that search alone isn't the whole story.
Where else you'll see it
Video game characters finding their way around obstacles, robots planning movement, and puzzle solvers all use A*-style search. Anywhere there's a goal and a sensible "how close am I?" estimate, it fits.
In the code, what happens if the heuristic always returns 0 for A*?
- It behaves like Dijkstra
- It never finds the goal
- It finds a shorter path than Dijkstra
Show the answer
It behaves like Dijkstra. Ranking by cost so far plus 0 is just ranking by cost so far, which is exactly Dijkstra's ripple. That's what search(False) does.
- Move goal to (18, 1)
- Delete the wall at x=14
- Multiply the heuristic by 3
- Move start to (1, 12)
The code
Python, with what each line means beside it. It compares the clever way with Dijkstra exploring evenly in all directions.
import heapqBorrow Python's priority-queue tool W, H, C = 20, 14, 14Grid is 20 by 14, cells 14pxwalls = {(9, y) for y in range(2, 12)} | {(14, y) for y in range(4, 14)}Two walls, each with a gapstart, goal = (1, 6), (18, 6)Pick start and goal cells def search(use_h):Define a search, with or without guessing h = lambda c: abs(c[0]-goal[0]) + abs(c[1]-goal[1]) if use_h else 0Guess remaining distance, or always zero best, came, seen = {start: 0}, {}, []Track best costs, parents, and visit order queue = [(h(start), 0, start)]Queue starts with just the start while queue:Repeat while cells are waiting _, g, cell = heapq.heappop(queue)Pop the most promising cell if g > best[cell]: continueSkip it if a better route exists seen.append(cell)Record that we visited it if cell == goal: breakStop once we reach the goal x, y = cellSplit the cell into x and y for nxt in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:Look at the four neighbors ok = 0 <= nxt[0] < W and 0 <= nxt[1] < H and nxt not in wallsCheck neighbor is on grid, not a wall if ok and g + 1 < best.get(nxt, 999):If this route to it is cheaper best[nxt], came[nxt] = g + 1, cellRemember the cost and where we came from heapq.heappush(queue, (g + 1 + h(nxt), g + 1, nxt))Queue it, ranked by cost plus guess path = [goal]Start the path at the goal while path[-1] != start:Until we're back at the start path.append(came[path[-1]])Step to the cell we came from return seen, pathHand back visits and path def draw(seen, path, ox):Define a function that paints one grid for x in range(W):Loop over every column for y in range(H):Loop over every row rect(ox + x*C, y*C, C-1, C-1, "#2b2d42" if (x, y) in walls else "#f1f3f5")Paint walls dark, open cells light for x, y in seen: rect(ox + x*C, y*C, C-1, C-1, "#a5d8ff")Tint every visited cell blue for x, y in path: rect(ox + x*C, y*C, C-1, C-1, "#ff922b")Paint the final path orange size(600, 230)Make a wide canvasbackground("white")White backgrounddseen, dpath = search(False)Run the obvious way: no guessingaseen, apath = search(True)Run the clever way: with guessingdraw(dseen, dpath, 10)Draw Dijkstra on the leftdraw(aseen, apath, 310)Draw A* on the righttext("Dijkstra", 10, 218, "black")Label the left gridtext("A*", 310, 218, "black")Label the right gridshow([len(dseen), len(aseen)], "cells visited: Dijkstra vs A*")Chart how many cells each visited- the only difference line 8With use_h False the guess is always 0, so this exact search behaves as plain Dijkstra. One flag swaps the algorithms.
- stale entries line 13A cell can be queued twice if a cheaper route turns up later. The older, costlier entry is skipped when popped.
- the ranking line 21Priority is cost so far plus estimated cost left. That sum is what pulls the search toward the goal.
Read more
- en.wikipedia.org: A* search
- Ask Bento: Why must the guess never overestimate?
- Ask Bento: What are contraction hierarchies?
- Ask Bento: How does BFS compare to Dijkstra?
Run it. Then change it.
The code runs right in the page and draws as it goes. Free, nothing to install.