ghfS44285618G08381g, heap = {S: 0}, [(h(S), S)]2while heap:3 f, v = heappop(heap)4 if v == G: return g[v]5 for w in nbrs(v):6 if g[v] + 1 < g.get(w, INF):7 g[w] = g[v] + 18 heappush(heap, (g[w] + h(w), w))68285814871038610251043smallest flargest46810810881088888
Tiles: one cell each; the number is its f = g + hTray: the heap, in pop order, smallest f on the leftA hopping token: one heappush or heappopEvery heappush and heappop of the real Python program, replayed: a token carrying f = g + h hops from a tile into the heap tray, and the smallest token hops back to its tile when it is popped. Moves away from G raise f by 2; moves toward G keep it the same, so A* walks around the wall and reaches G after 9 pops. With h = 0 the same loop is Dijkstra's algorithm and pops all 18 open tiles.

The guess

  1. Start at S and reach G. Each move goes up, down, left or right and costs 1. The tall blocks are walls. Dijkstra's algorithm would find the shortest route, but it searches in every direction. A* aims at G.

Running A*

Why it works

What happens

;; step 1/9 · the-task
grid: 4 rows x 5 columns, (row, column) from the top left
  . # . . .
  . # . . .
  . . . . .
  . . . . .
S = (0,0), G = (0,4)
each move: 1 step, up / down / left / right
open cells: 18, walls: 2

The tray shows the entries in the order heappop would return them. Inside, heapq keeps a binary heap in a plain list, which is only partly sorted; heap[0] is always the smallest. Several entries can share the smallest f. The heap holds (f, cell) tuples, and Python compares tuples item by item, so a tie goes to the cell with the smaller (row, column). A different tie rule pops other cells but finds a route of the same length.