Sub topic 6
Implementing A* with a Binary Heap
This chapter turns the A* procedure from the previous chapter into working Python. It assumes you can read Python, know how a binary heap supports push and pop in O(log n) time, and are comfortable with Big-O notation. It also assumes you already know what g, h, and f mean. The questions here are practical: which data structures to use, how to handle a node that is reached more than once, and how to recover the path at the end.
The Four Data Structures
A* keeps four pieces of state. Each one answers a different question during the search.
| Structure | Python type | Question it answers |
|---|---|---|
| Open list | `list` used as a heap via `heapq` | Which node should be expanded next? |
| Best cost so far | `dict` mapping node to `g` | What is the cheapest known cost to reach this node? |
| Parent map | `dict` mapping node to predecessor | How did we reach this node on its best known path? |
| Closed set | `set` | Has this node already been expanded? |
The open list is a min-heap ordered by f = g + h. Popping from it gives you the frontier node with the lowest estimated total cost. The g and parent dictionaries grow together: whenever you find a cheaper route to a node, you update both. The closed set records nodes that have been expanded, so you never expand the same node twice.
The Complete 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')The function makes no assumptions about the problem domain. neighbors(node) yields (successor, edge_cost) pairs, and h(node) returns the heuristic estimate. Nodes can be any hashable value: tuples for grid cells, strings for city names, or frozen tuples for puzzle states.
Design Decisions in Detail
Why the heap entries carry a counter
heapq compares tuples element by element. When two entries have the same f, Python moves on to the second element. Without the counter, that second element would be the node itself. That causes two problems. If nodes are objects without an ordering, Python raises TypeError: '<' not supported. If nodes are tuples, the comparison works but the order among equal-f entries depends on the node's coordinates, which has nothing to do with the search.
A monotonically increasing counter from itertools.count() makes every entry unique at the second position, so the comparison never reaches the node. As a side effect, entries with equal f come out in insertion order. A later chapter covers better tie-breaking policies. The counter is mainly there so the code works for any node type.
Lazy deletion instead of decrease-key
The textbook version of A* says: if you find a cheaper path to a node already in the open list, lower its priority. Python's heapq has no decrease-key operation. Adding one means tracking each node's index inside the heap, which is fiddly and easy to get wrong.
The standard workaround is lazy deletion. You push a new entry with the better f and leave the old one in the heap. The better entry has a lower f, so it is popped first and the node gets expanded with the correct g. When the old entry surfaces later, the if node in closed: continue line discards it. Those leftover entries are called stale entries.
The cost is a larger heap. Each successful relaxation pushes one entry, so the heap can hold up to O(E) entries rather than O(V), where E is the number of edges examined and V the number of nodes. Since log E ≤ 2 log V, each heap operation still costs O(log V) asymptotically. Total running time is O(E log V) in the worst case, the same bound as Dijkstra with a binary heap.
Testing for the goal on pop, not on push
The goal check happens when a node is popped from the heap, not when it is first generated as a neighbor. This matters for correctness. The first time you generate the goal, you have found a path to it, but a cheaper one may still be waiting in the frontier.
Consider edges S→G costing 10, S→A costing 1, and A→G costing 1, with h = 0 everywhere. Expanding S generates G with g = 10. If you returned there, you would report cost 10. Testing on pop, the search expands A next (f = 1), finds G at g = 2, pushes that entry, and pops G with cost 2. Only when a node leaves the heap does A* know its g is final, and that guarantee also depends on the heuristic, as later chapters show.
Path reconstruction from the parent map
Storing the full path in every heap entry would cost O(path length) memory per entry. The parent map stores one predecessor per node instead. When the goal is popped, you walk parent from the goal back to the start (whose parent is None) and then reverse the list. This takes O(path length) time once, at the end.
The parent map stays correct under lazy deletion because parent[nxt] is overwritten in the same step as g[nxt]. The parent always matches the best known cost.
Running It on a Grid
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(cost) # 5
print(len(path)) # 6 cells: start, four intermediate cells, goalThe grid has 4-connected moves with unit cost, and # cells are walls. Manhattan distance fits this movement model; the chapter on grid heuristics explains why. The neighbor function is a closure over the grid, so astar itself knows nothing about grids.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Heap entries are `(f, node)` | `TypeError` on custom node types, or ordering depends on node values | Insert a counter as the second element |
| Goal checked when pushed | Path is valid but sometimes too expensive | Check `node == goal` after popping |
| No stale-entry check | Nodes expanded several times, much slower search | Skip popped nodes that are already closed |
| `parent` updated without `g`, or the reverse | Reconstructed path does not match the reported cost | Update both in the same branch |
| Unhashable nodes such as lists | `TypeError: unhashable type` | Use tuples or frozen dataclasses |
| Using `<=` in the relaxation test | Redundant pushes and parent churn on ties | Use strict `<` |
Edge Cases
- Start equals goal. The first pop returns
([start], 0). No special case is needed. - Unreachable goal. The heap empties and the function returns
(None, inf). On a very large or infinite graph this can take a very long time or never finish, so production code often adds a node-expansion limit. - Zero-cost edges. These work as long as costs are non-negative. Negative edge costs break A* and Dijkstra alike.
- Floating-point costs. With octile or Euclidean costs, two routes of equal true length can differ in their last bits. This affects only which equal-cost path gets returned.
Exercise
Modify the heap entries to (f, tie, gatpush, node) and replace the closed-set check with a stale check based on g. What condition should cause a popped entry to be skipped, and why is it still correct to return when the goal is popped?
Show answer
Skip the entry when gatpush > g[node], because a cheaper path to that node was recorded after this entry was pushed. The entry that carries the current best g is still in the heap and has a lower f, so it is popped first. When the goal is popped with gatpush == g[goal], that is the cheapest goal entry in the frontier, and under a consistent heuristic that cost is optimal.
Exercise
On a graph with V nodes and E edges, what is the largest number of entries the heap can hold under lazy deletion, and how does that affect the running time compared with a decrease-key heap?
Show answer
Each successful relaxation pushes one entry, and each edge can succeed at most once per expansion of its source node, so the heap holds O(E) entries. Heap operations cost O(log E) = O(log V) because E ≤ V², so the total stays O(E log V). The price is extra memory for stale entries, not a worse time bound.
Exercise
Graph: S→A cost 2, S→B cost 1, B→A cost 0.5, A→G cost 1, with h = 0 everywhere. Trace the implementation and give the returned path and cost.
Show answer
Pop S, which pushes A (g=2) and B (g=1). Pop B, which improves A to g=1.5, sets parent[A]=B, and pushes it. Pop A at f=1.5, which pushes G (g=2.5). The stale A entry at f=2 is popped next and skipped because A is closed. Pop G and return path [S, B, A, G] with cost 2.5.