Sub topic 9
Why A* Returns Optimal Paths
This chapter assumes you have already seen the A loop with its binary heap, closed set, and parent pointers. It also assumes you know what admissible and consistent heuristics are. It answers three questions: when A is guaranteed to find a path at all (completeness), when the first goal it pops is the cheapest one (optimality), and which implementation details quietly break those guarantees.
Notation used throughout:
g(n)is the cost of the best path tonfound so far.g*(n)is the true cheapest cost from the start ton.h(n)is the heuristic.h*(n)is the true cheapest cost fromnto the goal.C*is the cost of an optimal solution.f(n) = g(n) + h(n).
Completeness: When A* Finds Some Path
A* is complete, meaning it returns a solution whenever one exists, under these conditions:
- Every node has finitely many successors (finite branching factor).
- Every edge costs at least some fixed ε > 0.
- A solution with finite cost exists.
Under these conditions, only finitely many nodes have f(n) ≤ C*. A drains them in finite time and reaches the goal. If the graph is finite, condition 2 can be relaxed to "no negative edges", because the closed set stops A from expanding the same node forever.
When the conditions fail, so does completeness:
| Violation | What goes wrong |
|---|---|
| Negative edge costs | `g` values can keep dropping. Closed nodes become wrong, and negative cycles have no cheapest path at all. |
| Zero-cost cycles in an infinite graph | A* can keep expanding nodes without `f` ever growing. |
| Edge costs shrinking toward 0 (1, 1/2, 1/4, ...) | An infinite path can have finite total cost, so A* never reaches nodes with larger `f`. |
| Infinite branching | One expansion never finishes. |
Optimality with an Admissible Heuristic
The core argument rests on one invariant.
Invariant. Until the goal is popped, the open list contains a node n that lies on some optimal path and already has g(n) = g*(n).
The start node satisfies this at the beginning. When such an n is expanded, its successor on the optimal path receives its optimal g and enters the open list, so the invariant carries forward.
For that node n:
f(n) = g*(n) + h(n) ≤ g*(n) + h*(n) = C*The inequality uses admissibility: h(n) ≤ h*(n).
Now suppose A pops the goal with cost `C > C. Because h(goal) = 0, the goal's priority is f = C. But n is still waiting in the open list with f(n) ≤ C < C, and a min-heap pops the smaller value first. That is a contradiction, so the first time the goal is popped, its cost is C`.
Where the invariant breaks
The invariant needs n to be in the open list with optimal g. Tree search (no closed set) keeps it trivially. A* with a closed set that never reopens nodes can violate it: a node can be closed with a suboptimal g, and when a cheaper route arrives later, that route is thrown away. With an admissible but inconsistent heuristic, that really happens.
A Counterexample You Can Run
The graph below has an optimal path S → A → C → G costing 5. The heuristic is admissible at every node. It is inconsistent on edge A → C: h(A) = 4 exceeds c(A, C) + h(C) = 1 + 0.
The code runs A* both with and without reopening closed nodes. It also checks consistency edge by edge.
import heapq
from itertools import count
def astar(start, goal, graph, h, reopen):
tie = count()
heap = [(h[start], next(tie), 0, start)]
g = {start: 0}
parent = {start: None}
closed = set()
expansions = 0
while heap:
_, _, g_entry, node = heapq.heappop(heap)
if g_entry > g[node]:
continue # stale entry: a cheaper route to node was pushed later
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], g[goal], expansions
closed.add(node)
expansions += 1
for nxt, cost in graph[node]:
if nxt in closed and not reopen:
continue # classic graph search: closed nodes are final
new_g = g[node] + cost
if new_g < g.get(nxt, float('inf')):
g[nxt] = new_g
parent[nxt] = node
heapq.heappush(heap, (new_g + h[nxt], next(tie), new_g, nxt))
return None, float('inf'), expansions
def inconsistent_edges(graph, h):
return [(n, m) for n in graph for m, c in graph[n] if h[n] > c + h[m]]
graph = {
'S': [('A', 1), ('C', 3)],
'A': [('C', 1)],
'C': [('G', 3)],
'G': [],
}
h = {'S': 0, 'A': 4, 'C': 0, 'G': 0}
print(inconsistent_edges(graph, h)) # [('A', 'C')]
print(astar('S', 'G', graph, h, reopen=False)) # (['S', 'C', 'G'], 6, 3)
print(astar('S', 'G', graph, h, reopen=True)) # (['S', 'A', 'C', 'G'], 5, 4)Here is what happens without reopening. S is expanded first. C has f = 3 + 0 = 3 and A has f = 1 + 4 = 5, so C is popped and closed with g = 3. G is pushed with f = 6. Next A is expanded and finds C at cost 2, but C is closed, so the cheaper route is discarded. G is popped with cost 6, which is not optimal.
With reopening, C goes back into the heap with g = 2. It is expanded again and pushes G with f = 5, which is popped before the stale f = 6 entry. The result is optimal, but the search costs one extra expansion. On bad inputs, reopening can cost exponentially many re-expansions.
Optimality with a Consistent Heuristic
Consistency, h(n) ≤ c(n, m) + h(m) with h(goal) = 0, removes the need for reopening. Two facts follow from it.
Fact 1: f never decreases along a path. For an edge n → m:
f(m) = g(n) + c(n, m) + h(m) ≥ g(n) + h(n) = f(n)So A* pops nodes in nondecreasing order of f.
Fact 2: a node's first pop has optimal g. Suppose m is popped with g(m) > g*(m). By the invariant, some node n on an optimal path to m is in the open list with optimal g. By Fact 1 applied along that optimal path, f(n) ≤ g*(m) + h(m) < g(m) + h(m). Then n would be popped before m, which is a contradiction.
Fact 2 means a closed node is final, so skipping closed nodes is safe. Each node is expanded at most once. The tutorial's reference implementation relies on exactly this, which is why it requires a consistent h.
Consistency also implies admissibility. Apply the inequality repeatedly along an optimal path from n to the goal: the edge costs add up to h*(n) and the chain ends at h(goal) = 0, so h(n) ≤ h*(n). The reverse does not hold, as the counterexample shows.
Summary of Guarantees
| Heuristic | Search style | Optimal? | Expansions per node |
|---|---|---|---|
| Admissible | Tree search (no closed set) | Yes | Unbounded on graphs with cycles |
| Admissible | Graph search with reopening | Yes | Can be more than one |
| Admissible, inconsistent | Graph search, closed nodes final | Not guaranteed | At most one |
| Consistent | Graph search, closed nodes final | Yes | At most one |
| Inadmissible | Any | No (bounded for weighted A*) | Depends |
Optimal Efficiency
With a consistent heuristic, A expands every node with `f(n) < C, some nodes with f(n) = C, and no node with f(n) > C. Any algorithm that is guaranteed optimal and uses the same heuristic information must also expand every node with f(n) < C`, because otherwise it could miss a cheaper path hidden behind one of them. In that sense A is optimally efficient. The only freedom left is among nodes with f = C*, which is where tie-breaking matters (covered in a later chapter).
Practical Gotchas
- Floating-point heuristics. Octile and Euclidean distances involve
sqrt(2). If edge costs andhare rounded differently,hcan overshoot the true cost by about 1e-12 and become slightly inadmissible. Use the same constant in both, or subtract a small epsilon fromh. - Mismatched movement models. Octile distance is consistent for 8-connected moves with diagonal cost
sqrt(2). Used on a map where diagonals cost 1, it overestimates. Chebyshev distance is the correct heuristic there. - Stale-entry handling. Lazy deletion (pushing duplicates and skipping them on pop) is correct only if the skip test cannot drop the current best entry. Check either the closed set (for consistent
h) org_entry > g[node]. - Reported cost vs path cost. If your code updates
gof a closed node without reexpanding it,parentpointers andg[goal]can disagree. Either never touch closed nodes or reopen them.
Exercise
A heuristic has h(goal) = 0 and satisfies h(n) ≤ h(n) everywhere, but violates consistency on one edge. Your A uses a closed set and never reopens nodes. Is the result guaranteed optimal? What is the smallest code change that restores the guarantee?
Show answer
It is not guaranteed. A node can be closed with a suboptimal g, and a later cheaper route to it is discarded, as in the S, A, C, G example (cost 6 instead of 5). Allowing closed nodes to be updated and pushed again when a strictly smaller g is found, and expanding them again when popped, restores optimality. Alternatively, drop the closed set and use tree search on a graph without problematic cycles.
Exercise
Show that with a consistent heuristic, the sequence of f-values popped from the heap (ignoring stale entries) is nondecreasing.
Show answer
When node n is popped with value f(n), every successor m it pushes has f(m) = g(n) + c(n, m) + h(m) ≥ g(n) + h(n) = f(n) by consistency. Every entry already in the heap had value ≥ f(n), because n was the minimum. So after the pop, every entry in the heap is ≥ f(n), and the next pop is too. Induction over the pops gives the result.
Exercise
A programmer returns as soon as the goal is generated as a neighbor, before pushing it. Construct a three-node graph where this returns a suboptimal path even with h = 0.
Show answer
Use edges S→G cost 10, S→A cost 1, A→G cost 1. Expanding S generates G with g = 10, and the early return gives cost 10. Popping instead orders the heap as A (1) then G (10). Expanding A pushes G with g = 2, which is popped first, so the result has the optimal cost 2.