Sub topic 13
Designing Heuristics by Relaxing the Problem
Earlier chapters judged heuristics after the fact. You were handed a function h and asked whether it was admissible, whether it was consistent, and whether it dominated another one. This chapter goes the other way and shows how to build a good heuristic from scratch. The method is called problem relaxation, and most heuristics you have seen so far, including Manhattan distance on grids, come from it.
This chapter assumes you know the A* loop from the implementation chapter, the definitions of admissibility and consistency, and heuristic dominance measured by nodes expanded.
The core idea
A relaxed problem is the original problem with one or more constraints removed. Every action that is legal in the original problem stays legal, and the relaxation usually adds new actions. Because the relaxed problem allows more moves, its cheapest solution can never cost more than the original problem's cheapest solution.
That gives a recipe:
- Write down the rules that define legal moves.
- Delete or weaken one or more conditions.
- If the resulting problem can be solved exactly and quickly, use its optimal cost from state
nash(n).
The output of step 3 is admissible by construction. You do not have to prove admissibility separately for each heuristic.
Why relaxed costs are admissible and consistent
Let G be the original state graph and G' the relaxed graph. Relaxation means two things:
- every edge of
Galso appears inG', and - each such edge costs no more in
G'than inG, soc'(n, n') ≤ c(n, n').
Define h(n) = d'(n, goal), the exact shortest-path cost in G'.
Admissibility. Any path in G is also a path in G' with equal or lower cost. So the cheapest path in G' costs at most the cheapest path in G, which gives h(n) ≤ h*(n).
Consistency. Shortest-path distances satisfy the triangle inequality in their own graph. For any edge (n, n') of G:
h(n) = d'(n) ≤ c'(n, n') + d'(n') ≤ c(n, n') + h(n')
That is exactly the consistency condition. The goal has distance zero in G', so h(goal) = 0.
Worked example: the 8-puzzle
The 8-puzzle has tiles 1 to 8 and one blank on a 3×3 board. Each move slides a tile into the blank and costs 1. The movement rule can be written as a single condition:
A tile can move from square A to square B if A is adjacent to B and B is blank.
Dropping parts of this rule produces three classic heuristics.
| Rule kept | Constraint dropped | Relaxed problem's optimal cost |
|---|---|---|
| A adjacent to B | B must be blank | Sum of Manhattan distances of tiles to their goal squares |
| B is blank | A must be adjacent | Gaschnig's heuristic: number of swaps with the blank needed to sort the board |
| nothing | both | Number of misplaced tiles |
Each relaxed problem is easy to solve. With the blank condition gone, tiles stop interfering with each other, so each tile walks its own shortest grid path and the costs add up. With both conditions gone, each misplaced tile needs exactly one move.
The diagram also shows dominance. A relaxation that keeps more constraints is "tighter," so its optimal cost is at least as large. Manhattan dominates misplaced tiles because removing the adjacency constraint as well can only make the problem cheaper. In general, if relaxation R2 is a relaxation of R1, then h_R1 dominates h_R2.
Running the comparison
The script below is self-contained. It scrambles the goal with random legal moves, so the start state is always solvable, and it counts the nodes A* expands under each heuristic.
import heapq
import random
from itertools import count
GOAL = (1, 2, 3, 4, 5, 6, 7, 8, 0) # 0 is the blank
GOAL_POS = {tile: divmod(i, 3) for i, tile in enumerate(GOAL)}
def neighbors(state):
b = state.index(0)
r, c = divmod(b, 3)
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < 3 and 0 <= nc < 3:
j = nr * 3 + nc
s = list(state)
s[b], s[j] = s[j], s[b]
yield tuple(s), 1
def misplaced(state):
# Relaxation: a tile may jump to any square in one move.
return sum(1 for i, t in enumerate(state) if t != 0 and t != GOAL[i])
def manhattan(state):
# Relaxation: a tile may move to any adjacent square, blank or not.
total = 0
for i, t in enumerate(state):
if t != 0:
r, c = divmod(i, 3)
gr, gc = GOAL_POS[t]
total += abs(r - gr) + abs(c - gc)
return total
def astar_count(start, goal, neighbors, h):
tie = count()
open_heap = [(h(start), next(tie), start)]
g = {start: 0}
closed = set()
expanded = 0
while open_heap:
_, _, node = heapq.heappop(open_heap)
if node in closed:
continue
if node == goal:
return g[node], expanded
closed.add(node)
expanded += 1
for nxt, cost in neighbors(node):
new_g = g[node] + cost
if new_g < g.get(nxt, float('inf')):
g[nxt] = new_g
heapq.heappush(open_heap, (new_g + h(nxt), next(tie), nxt))
return None, expanded
def scramble(state, moves, seed):
rng = random.Random(seed)
for _ in range(moves):
state = rng.choice([s for s, _ in neighbors(state)])
return state
start = scramble(GOAL, 60, seed=7)
for name, h in [("zero", lambda s: 0), ("misplaced", misplaced), ("manhattan", manhattan)]:
cost, expanded = astar_count(start, GOAL, neighbors, h)
print(f"{name:10s} cost={cost} expanded={expanded}")All three runs report the same cost, because all three heuristics are admissible and consistent. The expansion counts should decrease from zero to misplaced to manhattan, usually by an order of magnitude or more at each step. Try several seeds and longer scrambles to see how the gap grows with solution depth.
Relaxation beyond puzzles
The same reasoning explains heuristics from earlier chapters and extends to new domains.
| Domain | Constraint removed | Heuristic obtained |
|---|---|---|
| 4-connected grid with walls | Walls | Manhattan distance |
| 8-connected grid with walls | Walls | Octile distance |
| Any planar map | Walls and the grid itself | Euclidean (straight-line) distance |
| Road routing by travel time | The road network; drive at the top speed limit | Straight-line distance ÷ maximum speed |
| Planning with preconditions and effects | Delete effects of actions | Delete-relaxation heuristics such as h_max |
The road example shows that you can relax costs as well as moves. Dividing by the fastest speed anywhere on the map gives a time that no real route can beat.
Combining several relaxations
You often have several admissible heuristics and none dominates the others on every state. Take their pointwise maximum:
def max_heuristic(*hs):
return lambda n: max(h(n) for h in hs)
h = max_heuristic(manhattan, misplaced)The maximum of admissible heuristics is admissible, because each one is at most h*(n). The maximum of consistent heuristics is also consistent. It dominates every component, and its cost is the sum of the components' costs.
Do not add heuristics together unless they count disjoint costs. Manhattan plus misplaced tiles counts the same tile moves twice and can overestimate. Adding becomes safe when each move is charged to exactly one component, which is the idea behind additive pattern databases in the next chapter.
Common errors
- Relaxing too little. If the relaxed problem is as hard as the original, computing
hcosts as much as the search. Pick relaxations that decompose into independent subproblems, as Manhattan distance does by tile. - Relaxing too much. Each dropped constraint lowers
h. Misplaced tiles is cheap to compute but weak, so A* expands far more nodes with it. - Counting the blank. If misplaced tiles counts the blank, a state one move from the goal scores 2, which overestimates. The blank is a feature of the board, not an object that has to be moved.
- Changing the cost model by accident. A relaxation must never raise an edge cost. Using Manhattan distance on an 8-connected grid does exactly that, because one diagonal step is charged 2 when it really costs √2.
- Ignoring per-node cost. A heuristic that takes 50 times longer per node only pays off if it cuts expansions by more than that factor. Measure wall-clock time as well as node counts.
Exercise
In the 8-puzzle, consider a heuristic that counts how many tiles are in the wrong row plus how many tiles are in the wrong column. Which constraint does it relax, is it admissible, and how does it compare with Manhattan distance?
Show answer
In the relaxed problem a tile can jump to any square in an adjacent row or column in one move, ignoring the blank, so each tile needs one move to fix its row and one to fix its column. That is an exact relaxed cost, so the heuristic is admissible and consistent. It keeps adjacency in one dimension at a time but drops distance within a row or column, so Manhattan distance dominates it: Manhattan charges |dr| + |dc|, which is at least [dr ≠ 0] + [dc ≠ 0].
Exercise
A delivery robot moves on a 4-connected grid. Each step costs 1, and passing through a door cell costs an extra 3. Someone proposes h(n) = Manhattan distance + 3 × (number of door cells on the straight Manhattan route to the goal). Is this admissible? If not, propose a relaxation-based fix.
Show answer
It is not admissible. The optimal path may go around the doors, so a route that happens to cross a door can overcharge. One fix is to relax the walls but keep door costs only where they cannot be avoided: if every route from n to the goal must cross a known door (for example, a single door between two rooms), add 3 for that door and otherwise add nothing. Plain Manhattan distance, which drops door costs entirely, is always a safe fallback.
Exercise
Implement Gaschnig's heuristic for the 8-puzzle (the relaxed problem lets any tile swap with the blank from any square). Explain why it dominates misplaced tiles.
Show answer
Repeat until the board matches the goal: if the blank is not on its goal square, swap the blank with the tile that belongs on the blank's current square; otherwise swap the blank with any misplaced tile. Count the swaps. Every misplaced tile must move at least once in this relaxed problem, so the count is at least the number of misplaced tiles. Extra swaps are needed when the blank reaches home while other tiles are still misplaced, so the count is often strictly larger.