Sub topic 14
Weighted A*: Trading Optimality for Speed
This chapter assumes you already know the A loop from earlier chapters: the open heap ordered by f(n) = g(n) + h(n), the closed set, and path reconstruction through parent pointers. It also assumes you know what admissible and consistent heuristics are and why they make A optimal. Here we deliberately break optimality, but in a controlled way.
The Problem Weighted A* Solves
A with an admissible heuristic returns an optimal path, but it can expand a very large number of nodes to prove that the path is optimal. The waste comes from nodes that look about as good as the true best path. A has to look at all of them, because h underestimates and any of them might lead somewhere cheaper.
On a large game map or a robot planning grid, you often need a good path within a fixed time budget. A path that is 10% longer but found ten times faster is usually the better deal. Weighted A* gives you that trade, and it tells you in advance how much path quality you could lose.
The Evaluation Function with a Weight
Weighted A* changes one thing. It ranks nodes by
f_w(n) = g(n) + w · h(n), with w ≥ 1.
Everything else in the algorithm stays the same. Multiplying h by w makes the search trust the heuristic more than the cost already paid. Nodes that look close to the goal move up the queue, so the search heads for the goal instead of fanning out.
The weight places the algorithm on a spectrum:
| Weight | Behavior | Guarantee |
|---|---|---|
| w = 0 | Uniform-cost search (Dijkstra) | Optimal |
| w = 1 | Standard A* | Optimal with admissible h |
| 1 < w < ∞ | Weighted A* | Cost ≤ w × optimal |
| w → ∞ | Greedy best-first search (ties broken by g) | None |
Some texts write the function as f(n) = (1 − λ)·g(n) + λ·h(n) with λ between 0 and 1. Dividing by (1 − λ) gives the same ordering as w = λ / (1 − λ), so λ = 0.5 is plain A*.
Why the Cost Is Bounded by w Times the Optimum
Let C be the optimal cost and assume h is admissible. Weighted A stops when it pops the goal. At that moment the goal's key is f_w(goal) = g(goal), because h(goal) = 0.
Look at the optimal path from start to goal. Before the goal is popped, some node n on that path sits in the open list with its optimal cost-so-far, g(n) = g*(n). Its key is:
f_w(n) = g(n) + w · h(n) ≤ w · (g(n) + h(n)) ≤ w · C*
The first inequality holds because w ≥ 1 and g(n) ≥ 0. The second holds because h is admissible, so g(n) + h(n) can't exceed the cost of the optimal path through n, which is C. The heap popped the goal before n, so g(goal) ≤ f_w(n) ≤ w · C.
The bound is a worst case. In practice the returned path is often much closer to optimal than w predicts.
Implementation
The only change you need is to pass in a scaled heuristic. The script below is self-contained. It runs A* with an expansion counter on a 30×30 grid with a long wall, then compares several weights.
import heapq
from itertools import count
def astar(start, goal, neighbors, h):
tie = count()
open_heap = [(h(start), next(tie), start)]
g = {start: 0}
parent = {start: None}
closed = set()
expanded = 0
while open_heap:
_, _, node = heapq.heappop(open_heap)
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], g[goal], expanded
if node in closed:
continue
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
parent[nxt] = node
heapq.heappush(open_heap, (new_g + h(nxt), next(tie), nxt))
return None, float('inf'), expanded
def grid_neighbors(grid):
rows, cols = len(grid), len(grid[0])
def neighbors(cell):
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 grid[nr][nc] == '.':
yield (nr, nc), 1
return neighbors
def manhattan(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def weighted_h(h, w):
return lambda n: w * h(n)
def make_grid(n=30):
cells = [['.'] * n for _ in range(n)]
for r in range(n - 4): # wall down the middle, gap at the bottom
cells[r][n // 2] = '#'
return [''.join(row) for row in cells]
grid = make_grid()
start, goal = (0, 0), (0, 29)
base_h = lambda n: manhattan(n, goal)
for w in (1.0, 1.2, 1.5, 2.0, 5.0):
path, cost, expanded = astar(start, goal, grid_neighbors(grid),
weighted_h(base_h, w))
print(f"w={w:<4} cost={cost:<4} expanded={expanded}")The optimal cost on this map is 81. That is 26 steps down to the gap, 29 steps across, and 26 steps back up. With w = 1 the script prints cost 81. Larger weights expand fewer nodes and still report costs within w × 81. On this map they usually stay at 81, because many different paths share the optimal cost.
Gotchas and Failure Modes
The Weighted Heuristic Is Not Consistent
Even if h is consistent, w · h usually isn't. The search can close a node and then find a cheaper path to it later. The implementation above lowers g and changes parent for that node, but because the node is already closed it is never expanded again, so the improvement doesn't reach its descendants. You can handle this in two ways:
- Allow reopening. Remove the node from the closed set and expand it again. This gives better paths, but a node can be expanded many times.
- Never reopen. Skip closed nodes, as the code above does. Likhachev, Gordon, and Thrun (the ARA* paper, 2003) showed that the w-bound still holds without reopening when the base h is consistent. This is the common choice because it caps each node at one expansion.
A side effect of not reopening is that the reported cost (g of the goal) can be slightly higher than the true cost of the reconstructed path, because parent pointers may have been improved after their descendants were expanded. Either way, the reported cost is an upper bound that stays within w × C*.
More Weight Does Not Always Mean Fewer Expansions
Node counts usually drop as w grows, but they don't always drop. A heavily weighted search can dive into a dead end, such as a U-shaped obstacle facing the goal, and fill the whole pocket before it backs out. Plain A* would have spread out more evenly. Always benchmark on maps that look like your real workload.
Unit-Cost Grids Have Many Ties
On an open 4-connected grid, Manhattan distance is already exact and plain A expands few nodes. Weighting helps most when obstacles make h a weak estimate. If A is already fast on your maps, try better tie-breaking (preferring larger g) before you give up optimality.
Floating-Point Keys
With a non-integer w, keys that should be equal can differ slightly because of rounding. That doesn't affect correctness, because the counter in the heap tuple keeps ordering deterministic. It does mean tie-breaking can behave differently than it would with integer keys.
Choosing w and Related Variants
| Situation | Recommendation |
|---|---|
| Path quality matters, time is ample | w = 1 |
| Games, interactive planning | w between 1.1 and 2, tuned by benchmark |
| Hard real-time budget | Anytime search: ARA* starts with large w and lowers it while time remains |
| Bound must hold strictly and cheaply | Admissible base h, no reopening, consistent base h |
| Weighting causes dead-end dives | Lower w, or use focal search, which picks among near-best open nodes using a second heuristic |
Anytime repairing A (ARA) is the usual production pattern. It returns a quick path with w = 3 or so, then reuses the earlier search work to find better paths at smaller weights until time runs out or w reaches 1. Each intermediate path comes with its own bound.
Exercise
Weighted A runs with w = 1.5 and an admissible heuristic and returns a path of cost 120. What range must the optimal cost C lie in?
Show answer
The bound says 120 ≤ 1.5 · C, so C ≥ 80. The returned path is a real path, so C* ≤ 120. The optimal cost lies between 80 and 120.
Exercise
A colleague uses a heuristic that sometimes overestimates by up to 20% and runs weighted A* with w = 2. They claim the path is at most twice optimal. Are they right?
Show answer
No. The proof needs h to be admissible. A heuristic that overestimates by up to 20% can be written as h ≤ 1.2·h, so the effective weight on an admissible quantity is up to 2 × 1.2 = 2.4. The safe bound is 2.4 × C, not 2 × C*.
Exercise
Change the script so the search reopens closed nodes when it finds a cheaper g, and compare expansion counts and costs for w = 2 and w = 5. What do you expect to see?
Show answer
Before pushing a neighbor, discard it from closed (for example closed.discard(nxt)) inside the if new_g < ... branch. Expansion counts rise because some nodes are expanded more than once, and returned costs can only stay the same or drop. On this map both versions will likely return 81, which shows that reopening costs extra work and buys nothing here.