Sub topic 14
From Dijkstra to A* Search
This chapter assumes you have read the earlier chapters. In particular, you should know the heap-based implementation with lazy deletion, the predecessor map used for path reconstruction, early termination for single-target queries, and the greedy invariant behind Dijkstra's correctness. You should also be comfortable with Python tuples and closures.
Early termination lets Dijkstra stop once the target is popped. Before that point, it still searches in every direction equally. On a road map, a search from Paris to Berlin finalizes towns in Spain as readily as towns in Germany, as long as they are equally close to Paris. A* search keeps Dijkstra's structure and adds one piece of information: an estimate of how far each vertex still is from the target. That estimate tilts the search toward the goal.
The Core Idea: Order by g + h
Dijkstra pops the vertex with the smallest tentative distance from the source. In A this distance is usually called g(v). A adds a heuristic h(v), which is a function that estimates the remaining cost from v to the target. The heap is ordered by
f(v) = g(v) + h(v)
f(v) estimates the total cost of the best source-to-target path that passes through v. Vertices that lie roughly "on the way" have small f values and are expanded first. Vertices that lead away from the target have large h values, so they wait in the heap. Often they are never expanded at all.
Everything else stays the same as in Dijkstra: edge relaxation, the predecessor map, lazy deletion, and stopping when the target is popped. If you set h(v) = 0 for every vertex, A* becomes Dijkstra with early termination.
Implementation
The code below changes the earlier dijkstra_to_target in three places. The heap key becomes nd + h(v). The heap entry also carries g, so the code does not have to subtract h back out. The function returns the path and the number of expanded vertices, which makes the two algorithms easy to compare.
import heapq
def a_star(graph, source, target, h):
"""graph: dict node -> list of (neighbor, weight), weights >= 0.
h: function node -> estimated remaining cost to target."""
g = {source: 0}
prev = {}
heap = [(h(source), 0, source)] # (f, g, node)
closed = set()
while heap:
f, d, u = heapq.heappop(heap)
if u in closed:
continue # stale entry from lazy deletion
if u == target:
path = [u]
while path[-1] != source:
path.append(prev[path[-1]])
path.reverse()
return d, path, len(closed)
closed.add(u)
for v, w in graph.get(u, []):
nd = d + w
if v not in g or nd < g[v]:
g[v] = nd
prev[v] = u
heapq.heappush(heap, (nd + h(v), nd, v))
return None, None, len(closed)
def grid_graph(rows, cols):
"""Open grid, 4-way moves, every step costs 1."""
graph = {}
for r in range(rows):
for c in range(cols):
nbrs = []
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:
nbrs.append(((nr, nc), 1))
graph[(r, c)] = nbrs
return graph
graph = grid_graph(7, 7)
source, target = (3, 3), (3, 6)
def manhattan(v):
return abs(v[0] - target[0]) + abs(v[1] - target[1])
def zero(v):
return 0
print("A*: ", a_star(graph, source, target, manhattan))
print("Dijkstra:", a_star(graph, source, target, zero))
# A*: (3, [(3, 3), (3, 4), (3, 5), (3, 6)], 3)
# Dijkstra: (3, [(3, 3), (3, 4), (3, 5), (3, 6)], 19)Both runs find the same cost-3 path. Dijkstra (h = 0) expands 19 vertices: all 13 cells within distance 2 of the center, plus 6 cells at distance 3 that come before the target in tie order. A* expands only the 3 cells on the straight line. Every sideways step adds 1 to g and also adds 1 to h, so f rises from 3 to 5, and those entries are still in the heap when the target pops with f = 3.
What Makes a Heuristic Safe
A* returns correct shortest paths only if h meets certain conditions. There are two of them, and the difference between them matters in practice.
Admissible heuristics
A heuristic is admissible if it never overestimates: h(v) ≤ true distance from v to the target, for every v. With an admissible heuristic, the first time the target is popped, its g value is optimal. The reason is that any unexplored cheaper path would have some vertex in the heap with f ≤ the true optimal cost, and that vertex would have been popped first.
Consistent heuristics
A heuristic is consistent (also called monotone) if h(target) = 0 and, for every edge (u, v) with weight w:
h(u) ≤ w + h(v)
This is a triangle inequality. Every consistent heuristic is also admissible. Consistency is the property the code above relies on, because it uses a closed set and never reopens a closed vertex. Under consistency, f values along any path never decrease, so a vertex's g is final when it is popped. This is the same greedy invariant that makes Dijkstra correct.
A cleaner way to see this is through reduced costs. Define a new weight for each edge:
w'(u, v) = w(u, v) − h(u) + h(v)
Along any path from s to t, the h terms cancel in pairs, so every path's cost changes by the same constant, h(t) − h(s). The same path is shortest under both weightings. A* on the original weights behaves exactly like Dijkstra on the reduced weights. Consistency is the statement that every w' ≥ 0. Dijkstra needs non-negative weights, so the condition is the same one you met in the chapter on negative weights, moved onto the heuristic.
def is_consistent(graph, h, target):
if h(target) != 0:
return False
return all(h(u) <= w + h(v)
for u, edges in graph.items()
for v, w in edges)
print(is_consistent(graph, manhattan, target)) # True
print(is_consistent(graph, lambda v: 2 * manhattan(v), target)) # FalseRun this after the previous block. A check like this is cheap on small test graphs and catches heuristics that look sensible but break the guarantee.
Choosing a Heuristic
A heuristic is more informed the closer it gets to the true remaining distance. An admissible heuristic that is larger everywhere never expands more vertices than a smaller one, apart from tie-breaking. The perfect heuristic, h = true distance, expands only vertices on a shortest path. Computing it costs as much as solving the problem.
| Setting | Common heuristic | Notes |
|---|---|---|
| Grid, 4-way moves, unit cost | Manhattan distance | Consistent. Exact on an open grid. |
| Grid, 8-way moves, diagonal cost √2 | Octile distance | Manhattan would overestimate here. |
| Grid, any-angle movement | Euclidean distance | Consistent but weaker than octile on 8-way grids. |
| Road network, travel distance | Straight-line distance | Consistent, because roads are never shorter than a straight line. |
| Road network, travel time | Straight-line distance ÷ maximum speed | Uses the fastest possible speed so it stays admissible. Often weak in practice. |
| Large static graphs | Landmark bounds (ALT) | Precompute distances to a few landmarks and use the triangle inequality. |
Heuristic evaluation also has a cost. A heuristic that saves 30% of expansions but takes ten times longer per call than relaxing an edge is a net loss. Measure wall-clock time, not only expansion counts.
Common Errors and Failure Modes
Overestimating heuristics
If h overestimates, A* may return a path that is not shortest, and the code gives no warning. A typical bug is using Manhattan distance on a grid that allows diagonal moves, or forgetting to scale distance into the edge-weight unit, for example kilometers versus minutes.
Sometimes this is done on purpose. Weighted A* uses f = g + ε·h with ε > 1. It expands fewer vertices, and with a consistent h, the path it returns costs at most ε times the optimal. Games and robotics often accept this trade.
Forgetting the target in h
h must be built for a specific target. When you reuse a search object for several queries, a heuristic that captures the old target in a closure gives wrong answers. In the grid code, manhattan reads the global target, so changing target changes h. That works in a script but breaks easily in larger programs.
Expecting speedups where there are none
A helps only when h separates good directions from bad ones. In a maze where the true path winds far from the straight line, Manhattan distance is a loose bound. A then expands nearly as many vertices as Dijkstra and pays for the extra heuristic calls. A* also answers one source-target pair at a time. If you need distances from one source to every vertex, use plain Dijkstra, because no single heuristic can point toward all targets.
Negative weights
A* inherits Dijkstra's requirement that edge weights be non-negative. A heuristic cannot fix a negative edge. If the reduced cost w' is negative anywhere, the closed-set logic fails in the same way shown in the negative-weights chapter.
Decision Guide
| Need | Use |
|---|---|
| Distances from one source to all vertices | Dijkstra |
| One target, no useful distance estimate | Dijkstra with early termination |
| One target, consistent heuristic available | A* |
| One target, a near-optimal answer is acceptable and speed matters | Weighted A* |
| Negative edge weights | Bellman-Ford, not A* |
Exercise
On the 7×7 grid from this chapter, a teammate uses the heuristic h(v) = 2 × Manhattan distance to make A* "more focused." Is the result still guaranteed to be a shortest path? Explain using the consistency condition, then state the best bound you can give on the returned cost.
Show answer
No. For an edge (u, v) that moves one step toward the target, h(u) = h(v) + 2, so h(u) ≤ w + h(v) would require 2 ≤ 1, which is false. The heuristic is not consistent and also overestimates, since it is twice the true distance on an open grid, so optimality is lost. This is weighted A* with ε = 2 and a consistent base heuristic, so the returned path costs at most twice the optimal.
Exercise
Edge (u, v) has weight 4, h(u) = 10, and h(v) = 5. Compute the reduced cost w'(u, v) and say what it tells you about the heuristic.
Show answer
w' = 4 − 10 + 5 = −1. The reduced cost is negative, so h violates consistency on this edge: h(u) = 10 > w + h(v) = 9. A* with a closed set behaves like Dijkstra on a graph with a negative edge here and may close v's region too early with a suboptimal g.
Exercise
Why does A* with h(v) = 0 for every vertex expand exactly the same vertices, in the same order, as Dijkstra with early termination in this chapter's code?
Show answer
With h = 0, every heap entry is (g, g, v). That sorts by g first and then by vertex, which is the same order as Dijkstra's (g, v) entries. Relaxation, lazy deletion, and stopping at the target are unchanged, so the pop sequence is identical. In the grid example, both runs expand 19 vertices.