Sub topic 14
From Dijkstra to A* Search
This chapter assumes you know the heap-based Dijkstra implementation with lazy deletion, the early-termination version for a single target, and path reconstruction from a predecessor map. A* search, pronounced "A-star", changes one line of that early-terminating code: the key used to order the heap.
What Dijkstra Wastes on Single-Target Queries
Dijkstra expands vertices in order of their distance from the source, g(v). It has no idea where the target is. On a road map it grows a roughly circular frontier and settles thousands of vertices that lie in the wrong direction before it reaches the target.
A* adds a heuristic h(v), which estimates the remaining cost from v to the target. The heap is ordered by:
f(v) = g(v) + h(v), the cost so far plus the estimated cost still to go.
Vertices that look like they lie on a good route to the target come out of the heap first. The frontier stretches toward the target instead of spreading evenly.
The Implementation
The code below is the early-termination Dijkstra with h added to the heap key. Path reconstruction is built in.
import heapq
def a_star(graph, source, target, h):
"""graph: node -> list of (neighbor, weight); h: node -> estimated cost to target."""
g = {source: 0}
prev = {}
heap = [(h(source), source)]
closed = set()
while heap:
_, u = heapq.heappop(heap)
if u in closed:
continue # stale entry
if u == target:
path = [u]
while path[-1] != source:
path.append(prev[path[-1]])
path.reverse()
return g[u], path
closed.add(u)
for v, w in graph.get(u, []):
ng = g[u] + w
if v not in g or ng < g[v]:
g[v] = ng
prev[v] = u
heapq.heappush(heap, (ng + h(v), v))
return None, None
graph = {
"A": [("B", 4), ("C", 1)],
"C": [("B", 2), ("D", 5)],
"B": [("D", 1)],
"D": [],
}
estimate = {"A": 3, "B": 1, "C": 2, "D": 0}
print(a_star(graph, "A", "D", estimate.get)) # (4, ['A', 'C', 'B', 'D'])
print(a_star(graph, "A", "D", lambda v: 0)) # (4, ['A', 'C', 'B', 'D'])The second call uses h = 0. With that heuristic, A does exactly what Dijkstra does. Dijkstra is the special case of A with no information about the target.
When the Heuristic Is Safe
Whether A* returns the true shortest path depends on the properties of h:
| Heuristic property | Definition | Result |
|---|---|---|
| Zero | `h(v) = 0` for every vertex | Identical to Dijkstra |
| Admissible | `h(v)` never exceeds the true remaining cost | Optimal, provided vertices can be reopened |
| Consistent | `h(u) <= w(u, v) + h(v)` for every edge, and `h(target) = 0` | Optimal with the closed set above, which never reopens a vertex |
| Inadmissible | Sometimes overestimates | Often faster, but the path may not be the shortest |
Consistency gives you the same guarantee as the greedy invariant. Along any path the f values never decrease, so the first time a vertex is popped its g is final. That is why the closed set is safe here. Every consistent heuristic is also admissible.
Common consistent heuristics are straight-line distance on maps and Manhattan distance on 4-connected grids with unit step cost. A more accurate heuristic expands fewer vertices. The ideal heuristic is the exact remaining cost, which would expand only the vertices on the shortest path. A heuristic that is expensive to compute can cancel out the savings.
Exercise
On a 4-connected grid where each step costs 1, is Euclidean (straight-line) distance to the target admissible? Is it a better heuristic than Manhattan distance?
Show answer
Euclidean distance is admissible, and it is also consistent, because it never exceeds the Manhattan distance, and Manhattan distance is the true remaining cost on an empty grid. It is a worse heuristic, though. Manhattan distance is never smaller than Euclidean distance and is still admissible, so it guides the search more tightly and A* expands fewer vertices.
Exercise
In the example graph, change h("C") to 4 and leave the other estimates unchanged. Is this heuristic admissible? What does a_star return?
Show answer
It is not admissible. The true cost from C to D is 3, and the heuristic says 4. A* pops A, pushes B with f = 4 + 1 = 5 and C with f = 1 + 4 = 5, then pops B (the tie breaks on the name "B" < "C"). B pushes D with g = 5. Next it pops C, which improves B to g = 3, but B is already closed, so the improvement never reaches D. The function returns (5, ['A', 'B', 'D']), which is wrong. The true shortest cost is 4.