Sub topic 10
Choosing a Heuristic for Grid Maps
Grids are the most common place where people use A. Games, robot maps, and warehouse planners all reduce the world to cells. The right heuristic for a grid depends almost entirely on one question: how is the agent allowed to move, and what does each move cost?* If you pick a heuristic that doesn't fit the movement model, you either lose optimality (when it overestimates) or waste work (when it underestimates more than it needs to).
This chapter assumes you know the A* loop and the binary-heap implementation from earlier chapters. It also assumes you know the definitions of admissible (h never overestimates the true remaining cost) and consistent (h(n) ≤ c(n, m) + h(m) for every edge).
Movement models
A grid becomes a graph once you fix which neighbors each cell connects to and what each step costs. Four models cover most uses:
| Movement model | Moves allowed | Step costs | Matching heuristic |
|---|---|---|---|
| 4-connected | Up, down, left, right | 1 per step | Manhattan |
| 8-connected, true diagonals | Adds the 4 diagonals | 1 straight, √2 diagonal | Octile |
| 8-connected, cheap diagonals | Adds the 4 diagonals | 1 for every step | Chebyshev |
| Any-angle or continuous | Straight lines between points | Geometric length | Euclidean |
"Matching" has a specific meaning here. On a grid with no obstacles, the matching heuristic equals the exact shortest-path cost. Obstacles can only make real paths longer. So a heuristic that is exact on the empty grid is a lower bound on the obstructed grid, which makes it admissible.
The four formulas
Let dx = |x₁ − x₂| and dy = |y₁ − y₂|.
- Manhattan: dx + dy. With only orthogonal moves, you must cover every row and column of difference one step at a time.
- Chebyshev: max(dx, dy). When a diagonal step costs the same as a straight one, each step can close one unit in both axes at once.
- Octile: (dx + dy) + (√2 − 2)·min(dx, dy). You take min(dx, dy) diagonal steps at √2 each, then |dx − dy| straight steps. This simplifies to the formula shown.
- Euclidean: √(dx² + dy²). The straight-line distance.
On any pair of cells these satisfy:
Chebyshev ≤ Euclidean ≤ Octile ≤ Manhattan
The order matters for two reasons. A heuristic that is admissible for some model stays admissible if you swap in anything smaller. Anything larger can overestimate.
The admissibility matrix
Combining the ordering with the "exact on an empty grid" rule gives this matrix. A ✓ means admissible and consistent. A ✗ means it can overestimate.
| Heuristic | 4-connected | 8-connected, √2 diagonals | 8-connected, cost-1 diagonals |
|---|---|---|---|
| Manhattan | ✓ exact on open grid | ✗ | ✗ |
| Octile | ✓ | ✓ exact on open grid | ✗ |
| Euclidean | ✓ | ✓ | ✗ |
| Chebyshev | ✓ | ✓ | ✓ exact on open grid |
Read the matrix this way: in each column, use the largest heuristic that still has a ✓. Smaller admissible heuristics are still correct, but they expand more nodes. The chapter on dominance covers why.
Why consistency comes for free: the matching heuristic is the exact distance on the empty grid, and exact distances satisfy the triangle inequality. Adding obstacles, or banning corner-cutting, only removes edges. Every remaining edge still satisfies h(n) ≤ c(n, m) + h(m).
Checking it yourself
You can test a heuristic directly instead of trusting a table. Run Dijkstra backward from the goal to get the true cost-to-goal for every reachable cell. Then check h(n) ≤ true(n) for admissibility, and h(n) ≤ c(n, m) + h(m) on every edge for consistency. The script below does this for all four heuristics under all three grid models. It also runs A* and counts expansions.
import heapq
import math
from itertools import count
SQRT2 = math.sqrt(2)
INF = float('inf')
def manhattan(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def euclidean(a, b):
return math.hypot(a[0] - b[0], a[1] - b[1])
def chebyshev(a, b):
return max(abs(a[0] - b[0]), abs(a[1] - b[1]))
def octile(a, b):
dx, dy = abs(a[0] - b[0]), abs(a[1] - b[1])
return (dx + dy) + (SQRT2 - 2) * min(dx, dy)
def make_neighbors(grid, diagonal_cost=None):
rows, cols = len(grid), len(grid[0])
steps = [(1, 0, 1.0), (-1, 0, 1.0), (0, 1, 1.0), (0, -1, 1.0)]
if diagonal_cost is not None:
steps += [(dr, dc, diagonal_cost) for dr in (1, -1) for dc in (1, -1)]
def neighbors(cell):
r, c = cell
for dr, dc, cost in steps:
nr, nc = r + dr, c + dc
if not (0 <= nr < rows and 0 <= nc < cols) or grid[nr][nc] != '.':
continue
# No corner cutting: both orthogonal cells must be open.
if dr and dc and (grid[r][nc] != '.' or grid[nr][c] != '.'):
continue
yield (nr, nc), cost
return neighbors
def exact_costs(goal, neighbors):
# Dijkstra from the goal. Moves are symmetric, so this is cost-to-goal.
dist = {goal: 0.0}
heap = [(0.0, goal)]
while heap:
d, node = heapq.heappop(heap)
if d > dist[node]:
continue
for nxt, cost in neighbors(node):
nd = d + cost
if nd < dist.get(nxt, INF):
dist[nxt] = nd
heapq.heappush(heap, (nd, nxt))
return dist
def check(h, goal, neighbors, eps=1e-9):
dist = exact_costs(goal, neighbors)
admissible = all(h(n, goal) <= d + eps for n, d in dist.items())
consistent = all(h(n, goal) <= cost + h(m, goal) + eps
for n in dist for m, cost in neighbors(n))
return admissible, consistent
def astar_count(start, goal, neighbors, h):
tie = count()
open_heap = [(h(start, goal), next(tie), start)]
g = {start: 0.0}
closed = set()
while open_heap:
_, _, node = heapq.heappop(open_heap)
if node in closed:
continue
if node == goal:
return g[node], len(closed)
closed.add(node)
for nxt, cost in neighbors(node):
new_g = g[node] + cost
if new_g < g.get(nxt, INF):
g[nxt] = new_g
heapq.heappush(open_heap, (new_g + h(nxt, goal), next(tie), nxt))
return INF, len(closed)
grid = ["..........",
"..........",
"...####...",
"..........",
".........."]
start, goal = (0, 0), (4, 9)
models = {"4-connected": None,
"8-connected, sqrt2 diagonals": SQRT2,
"8-connected, cost-1 diagonals": 1.0}
heuristics = {"manhattan": manhattan, "euclidean": euclidean,
"octile": octile, "chebyshev": chebyshev}
for model_name, diag in models.items():
nb = make_neighbors(grid, diag)
print(model_name)
for h_name, h in heuristics.items():
adm, con = check(h, goal, nb)
cost, expanded = astar_count(start, goal, nb, h)
print(f" {h_name:10} admissible={adm!s:5} consistent={con!s:5} "
f"cost={cost:.3f} expanded={expanded}")The output should agree with the matrix. For example, cell (3, 8) sits one diagonal step from the goal. Manhattan reports 2 there, which exceeds the true cost in both 8-connected models. Within each model, every admissible heuristic returns the same path cost. The matching heuristic usually expands the fewest nodes.
Edge cases that break heuristics
Variable terrain costs
If cells have different costs (road 1, grass 2, swamp 5), the heuristic must assume the cheapest terrain all the way to the goal. Multiply the geometric heuristic by the minimum cost per unit of distance on the map. If a road costs 0.5 per step and you leave Manhattan unscaled, the heuristic overestimates along roads. A large minimum cost is a good thing: it makes h tighter. A single very cheap tile anywhere forces you to weaken h everywhere.
Units must match
The heuristic must be in the same units as the edge costs. If your edges cost 10 per straight step and 14 per diagonal (a common integer trick), use 10·dx + 10·dy − 6·min(dx, dy). Using plain octile in "cells" would underestimate by a factor of 10, and A* would degrade toward Dijkstra.
Floating point
With √2 costs, a sum such as g + h can come out slightly different for two equal-cost paths. This does not hurt correctness, but it does make tie-breaking erratic. It is also why the checker uses a tolerance. The 10/14 integer costs avoid the problem. They cost slightly less than true geometry, since 14 < 10√2 ≈ 14.142, and the integer octile above is exact for that model.
Corner-cutting rules
Banning diagonal moves past wall corners removes edges. Removing edges never breaks admissibility or consistency, so no change to h is needed.
Heuristic exact but search still slow
On an open grid with a matching heuristic, many cells tie on f because many shortest paths exist. A* can expand a wide band of them. That is a tie-breaking problem, covered in its own chapter. Changing heuristics will not fix it.
Exercise
A map is 8-connected with diagonals costing √2. Terrain costs are multipliers on step length: road 0.5, plain 1, forest 3. Write an admissible, consistent heuristic and explain why plain octile is not admissible.
Show answer
Use 0.5 × octile(n, goal). Plain octile assumes every unit of distance costs at least 1, but along a road it costs 0.5, so the true cost can be half of octile and plain octile would overestimate. Scaling by the minimum multiplier gives a lower bound everywhere. It stays consistent because octile is consistent on the unit-cost graph, and every real edge costs at least 0.5 times its unit-cost length.
Exercise
On an 8-connected grid with cost-1 diagonals, a teammate uses Euclidean distance because "straight lines are the shortest." Give a concrete counterexample showing it is inadmissible.
Show answer
From (0, 0) to (3, 3) on an open grid, three diagonal steps cost 3. Euclidean gives √18 ≈ 4.24, which is greater than 3. Chebyshev gives max(3, 3) = 3, which is exact.
Exercise
Your edges cost 10 (straight) and 14 (diagonal). Is the heuristic 10·max(dx, dy) admissible? Is it better or worse than 10(dx + dy) − 6·min(dx, dy)?
Show answer
It is admissible, because every step closes at most one unit along the larger axis and costs at least 10. It is weaker: 10(dx + dy) − 6·min(dx, dy) = 10·max(dx, dy) + 4·min(dx, dy), which is at least as large and is exact on an open grid. So the integer octile dominates it and expands no more nodes.