Sub topic 6
Implementing A* with a Binary Heap
This chapter assumes you can read Python, know what a binary heap is, and have followed the earlier chapters on f(n) = g(n) + h(n) and the step-by-step A* loop. Here we turn that loop into working code. The code has three parts: an open list, a closed set, and parent pointers for rebuilding the path.
The data structures
| Structure | Python type | Role |
|---|---|---|
| Open list | `heapq` list of `(f, tie, node)` | Frontier, popped in order of lowest f |
| `g` | `dict` | Best known cost from the start to each node |
| `parent` | `dict` | Predecessor on the best known path |
| Closed set | `set` | Nodes already expanded, never expanded again |
Python's heapq has no decrease-key operation. When we find a cheaper route to a node, we push a new entry and leave the old one in the heap. This technique is called lazy deletion. The old entry is "stale", and we discard it when it reaches the top because its node is already in the closed set. The heap may grow larger than the number of nodes, but each push and pop still costs O(log n).
The implementation
import heapq
from itertools import count
def astar(start, goal, neighbors, h):
tie = count()
open_heap = [(h(start), next(tie), start)]
g = {start: 0}
parent = {start: None}
closed = set()
while open_heap:
_, _, node = heapq.heappop(open_heap)
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], g[goal]
if node in closed:
continue
closed.add(node)
for nxt, cost in neighbors(node):
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 + h(nxt), next(tie), nxt))
return None, float('inf')
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
def manhattan(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
grid = ["....",
".##.",
"...."]
goal = (2, 3)
path, cost = astar((0, 0), goal, grid_neighbors(grid), lambda n: manhattan(n, goal))
print(path) # [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (2, 3)]
print(cost) # 5neighbors is a function that yields (node, edge_cost) pairs. Because of this, the same astar runs on grids, road maps, or puzzle states. Nodes only need to be hashable.
Common errors
- Testing for the goal when you push it. A cheaper path to the goal may still be in the heap. Test when you pop, as the code above does.
- Leaving out the tie counter. When two entries have the same f, Python compares the next tuple field. Without the counter, it compares the nodes themselves, which can raise
TypeErroror impose an ordering you didn't intend. - Forgetting the closed-set check after popping. The result is still correct, but stale entries get expanded again and work multiplies.
- Storing f without storing g. You need
g[node]to compute a neighbor's cost. Don't try to recover it as f − h.
Exercise
Suppose you replace the tuple (f, tie, node) with (f, node). The nodes are custom objects that don't define ordering. What goes wrong, and when does it happen?
Show answer
When two heap entries have the same f, heapq compares the nodes and raises TypeError, because the objects don't support "<". The failure shows up only when f values tie, so small tests may pass while larger maps crash. The counter prevents this and gives first-in, first-out order among ties.
Exercise
On the example grid, the heap holds more entries than there are open cells at some point. Why is this not a bug?
Show answer
Lazy deletion pushes a fresh entry each time a node's g improves and leaves the old entry in the heap. The closed-set check discards the stale entries when they are popped, so each node is expanded at most once.