Sub topic 13
Guiding the search with A*
This chapter assumes you know breadth-first search, Dijkstra's algorithm with a heap, and the grid neighbors function from earlier chapters. A* is Dijkstra with one change: it uses a guess about the remaining distance to decide which cell to expand next.
The idea
Dijkstra expands cells in order of dist, the cost already paid to reach them. It spreads out evenly in every direction, even away from the goal. A* orders the heap by dist + h(cell), where h is a heuristic: an estimate of the cost from cell to the goal. Cells that look closer to the goal are expanded first, so the search often visits far fewer cells.
Admissible heuristics
A* returns a cheapest path only if the heuristic is admissible: it never overestimates the true remaining cost. A heuristic that overestimates can steer the search past the best route.
On a 4-direction grid where every step costs at least 1, the Manhattan distance is admissible:
def manhattan(cell, goal):
return abs(cell[0] - goal[0]) + abs(cell[1] - goal[1])The right heuristic depends on the movement rules and costs:
| Movement | Admissible heuristic |
|---|---|
| 4 directions, minimum step cost 1 | Manhattan distance |
| 8 directions, all steps cost 1 | Chebyshev distance: `max(abs(dr), abs(dc))` |
| Any movement | `0`, which makes A* identical to Dijkstra |
If cells can cost less than 1, scale the heuristic by the smallest cost. Otherwise it overestimates.
A* on the cost grid
This version changes the Dijkstra function from the earlier chapter in two places: the heap key and the heuristic.
import heapq
def manhattan(cell, goal):
return abs(cell[0] - goal[0]) + abs(cell[1] - goal[1])
def astar_cost(cost, start, goal):
rows, cols = len(cost), len(cost[0])
best = {start: 0}
heap = [(manhattan(start, goal), 0, start)]
while heap:
_, dist, cell = heapq.heappop(heap)
if cell == goal:
return dist
if dist > best[cell]:
continue
r, c = cell
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and cost[nr][nc] is not None:
nd = dist + cost[nr][nc]
if nd < best.get((nr, nc), float('inf')):
best[(nr, nc)] = nd
priority = nd + manhattan((nr, nc), goal)
heapq.heappush(heap, (priority, nd, (nr, nc)))
return None
grid = [
[1, 1, 1, 1],
[1, None, None, 1],
[1, 1, 1, 1],
]
print(astar_cost(grid, (0, 0), (2, 3)))This prints 5. The heap holds (priority, dist, cell). Priority decides the order, and dist is stored so the stale-entry check still compares real costs. Every step costs at least 1, so Manhattan distance is admissible here.
Common errors
- Storing only the priority. If you push
g + hand later compare it tobest, which holdsg, the stale check misfires. Keepgin the tuple. - Overestimating. Using Manhattan distance on an 8-direction grid overestimates diagonal moves, so the path may not be cheapest.
- Expecting a speedup everywhere. With
h = 0, or in a maze where the straight line is blocked, A* expands about as many cells as Dijkstra. It is never worse in correctness, and the heuristic costs a little time per cell. - A heuristic with a weak model. A* needs positive step costs, like Dijkstra. Negative costs break both.
Exercise
A grid allows 8-direction movement, and every step, diagonal or not, costs 1. Which heuristic is admissible and as informative as possible among Manhattan, Chebyshev, and zero?
Show answer
Chebyshev distance, max(abs(dr), abs(dc)). A diagonal step covers one row and one column at once, so Manhattan distance can overestimate and is not admissible. Zero is admissible but gives no guidance. Chebyshev never overestimates and is the tightest of the three.