A* SEARCH
Dijkstra with a compass, and what happens when the compass lies
A* keeps an open set and always pops the node with the lowest f = g + h: cost so far plus a guess of the cost to go. It pops E and discovers the goal G through an 8-cost edge, giving g(G) = 11. The optimal path costs 9 and is not yet found. What should A* do?
A* is Dijkstra with a guess. For each node it tracks g, the cheapest cost found from the start, and h, an estimate of the cost still to go. It always expands the open node with the lowest f = g + h, and returns when it pops the goal.
If h never overestimates the true remaining cost, h is admissible and the returned path is optimal, provided the search reopens a closed node when a cheaper path to it turns up (as the sim does). A consistent h, one with h(u) ≤ w(u,v) + h(v) on every edge, never needs a reopen. This graph’s h is admissible but not consistent at S. A good h skips nodes that lead away from the goal. A bad h that overestimates can make a detour look cheap and hide the real shortest path.
A* (graph search with reopening)
f(n) = g(n) + W * h(n) W = 1: plain A*
g(n): cheapest cost found so far from start to n
h(n): estimate of the cost from n to the goal
open = {start}; g[start] = 0
while open not empty:
u = node in open with lowest f
if u == goal: return path(u), g[u] // only when POPPED
move u from open to closed
for (v, w) in neighbours(u):
if g[u] + w < g[v]:
g[v] = g[u] + w; prev[v] = u
put v in open (reopen it if it was closed)
Admissible: h(n) <= h*(n), the true remaining cost.
=> the returned path is optimal.
Consistent: h(u) <= w(u,v) + h(v). Stronger; then
no node ever needs reopening.
W > 1 (weighted A*): faster, cost <= W * optimal.
h = 0: A* is Dijkstra. Watch the RESULT box and the invariant strip. With W = 1, A* returns cost 9 after 5 expansions while Dijkstra needs 7. With h(C) raised to 8, C looks expensive, A* takes S→A→D→G and returns 10, and both invariants go red.
Weighted A* multiplies h by W to dive toward the goal and expand fewer nodes. Find the largest W that still returns the optimal path on this graph.
GOAL: optimal at W, suboptimal at W + 0.5
This A* returns as soon as it sees the goal. On the lesson graph it sees G from E first, through an 8-cost road, and returns 11. Make it return the optimal path. Every heuristic in the tests is admissible (it never overestimates); the random-graph ones are also consistent. Return null if the goal is unreachable.
Game and robot pathfinding on grids and navmeshes, map routing (with landmark heuristics and precomputed hierarchies), puzzle solvers, planners. Weighted A* and its variants show up wherever a good-enough path now beats the best path later.
“Implement A* on a grid” and “when is A* optimal?” Name admissibility, explain why the goal check belongs at pop time, give Manhattan distance as an admissible heuristic for 4-way grids, and say what weighted A* gives up.