Sub topic 14
Weighted A*: Trading Optimality for Speed
This chapter assumes you already know the A loop from earlier chapters: a heap ordered by f, a closed set, and path reconstruction. It also assumes you know that an admissible heuristic makes A optimal. Weighted A* changes one number in that loop. In return, it often expands far fewer nodes.
The Idea: Inflate the Heuristic
Plain A ranks nodes by f(n) = g(n) + h(n). Weighted A ranks them by:
f(n) = g(n) + w · h(n), with w ≥ 1
A larger w makes the search trust the heuristic more than the cost already paid. The search then pushes toward the goal and spends less time widening out around the start.
| Weight | Behavior | Guarantee |
|---|---|---|
| w = 1 | Standard A* | Optimal (admissible h) |
| 1 < w < ∞ | Goal-directed, fewer expansions | Cost ≤ w × optimal |
| w → ∞ | Behaves like greedy best-first | None |
Why the Bound Holds
Let C be the optimal cost. If h is admissible, then w · h overestimates by at most a factor of w. Every node on the optimal path therefore has an inflated f-value of at most w · C. The goal cannot be popped from the heap until its f, which equals its g, is no larger than the f of some node still waiting on the optimal path. So the returned cost is at most w · C*. The bound still holds when the search never reopens closed nodes, provided h is consistent. The code below makes that choice.
A Runnable Comparison
This version counts expansions so you can measure the speedup on a map with a wall.
import heapq
from itertools import count
def weighted_astar(start, goal, neighbors, h, w=1.0):
tie = count()
open_heap = [(w * h(start), next(tie), start)]
g = {start: 0}
parent = {start: None}
closed = set()
while open_heap:
_, _, node = heapq.heappop(open_heap)
if node in closed:
continue
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], g[goal], len(closed)
closed.add(node)
for nxt, cost in neighbors(node):
if nxt in closed:
continue # no reopening
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 + w * h(nxt), next(tie), nxt))
return None, float('inf'), len(closed)
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
grid = [['.'] * 20 for _ in range(20)]
for r in range(17):
grid[r][10] = '#' # wall with a gap at the bottom
start, goal = (0, 0), (0, 19)
h = lambda n: abs(n[0] - goal[0]) + abs(n[1] - goal[1])
for w in (1.0, 1.5, 2.0, 5.0):
path, cost, expanded = weighted_astar(start, goal, grid_neighbors(grid), h, w)
print(f"w={w}: cost={cost}, expanded={expanded}")The optimal cost here is 53. Run the script and compare the expansion counts. The exact numbers depend on the map and on tie-breaking, but higher weights usually expand fewer nodes.
Common Errors
- Treating w as a tuning knob without a bound. The w · C* guarantee only holds if the original h is admissible. Inflating an inadmissible heuristic gives no guarantee at all.
- Expecting monotone speedups. Higher w usually helps, but a trap like a dead-end pocket can make a goal-greedy search expand more nodes.
- Using w < 1. That shifts the search back toward uniform-cost search. It stays optimal but gets slower.
Exercise
An admissible heuristic gives an optimal cost of 40 on some map. You run weighted A* with w = 1.25. What is the largest path cost it may return, and what changes if h was not admissible?
Show answer
At most 1.25 × 40 = 50. If h was not admissible, the bound no longer holds, and the returned cost can exceed 50 by any amount.
Exercise
In the script above, why does the loop skip neighbors that are already in the closed set?
Show answer
Weighted A* can close a node before it has found that node's cheapest g. Skipping closed neighbors means the search never reopens nodes, which saves work. It also keeps the stored g-values consistent with the parent pointers, so the reported cost matches the reconstructed path. With a consistent h, the w-suboptimality bound still holds without reopening.