Sub topic 2
Implementing A* with a Binary Heap
This chapter assumes you know Python, know how a binary heap works through heapq, and know the evaluation function f(n) = g(n) + h(n) from the previous chapter.
The Implementation
A* keeps an open list of nodes waiting to be expanded, stored as a heap ordered by f. It also keeps a closed set of nodes already expanded, and a parent map used to rebuild the path at the end.
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, cost) # cost is 5heapq has no decrease-key operation, so the code pushes a new entry whenever it finds a cheaper g. When an older, stale entry for the same node is popped later, the closed-set check skips it. The counter breaks ties so the heap never has to compare two nodes directly.
Admissible Heuristics
A heuristic is admissible if h(n) ≤ h\(n) for every node, where h\(n) is the true cheapest cost from n to the goal. On a 4-connected grid with unit step costs, Manhattan distance is admissible because every move changes the row or the column by exactly 1.
Consistent Heuristics
A heuristic is consistent if h(goal) = 0 and, for every edge from n to n' with cost c(n, n'):
h(n) ≤ c(n, n') + h(n')
This is a triangle inequality. Every consistent heuristic is also admissible. Some admissible heuristics are not consistent.
Why A* Returns Optimal Paths
With a consistent h, f never decreases along any path. So the first time a node is popped, its g is already optimal. Now let C\ be the optimal cost. Until the goal is popped, some node on an optimal path is still in the open list, and its f is at most C\. The goal is popped with f = g(goal), and that pop happens only when no entry with a smaller f remains, so g(goal) ≤ C\. This also tells you which nodes A\ expands: every node with f < C\, and none with f > C\.
Exercise
On a 4-connected grid with unit step costs, is h(n) = 2 × Manhattan(n, goal) admissible? Explain why or why not.
Show answer
No. A node one step from the goal has a true cost of 1 but h = 2, so h overestimates the cost. A* using this h may return a path that is not optimal.
Exercise
An edge from A to B costs 2, with h(A) = 7 and h(B) = 4. Is h consistent on this edge?
Show answer
No. Consistency requires h(A) ≤ 2 + h(B) = 6, but h(A) = 7.