A star algorithm Python level
Run an A star algorithm Python level and inspect its distance heuristic beside Dijkstra.
Published here , updated · 3 sources · Resume reading
A star search keeps Dijkstra's cost-so-far and adds a Manhattan distance guess toward the goal [2]. ALGO ARCADE level 11 uses that heap key on the same dungeon as Dijkstra [1][3]. On that map both find cost 14 to the treasure, and A star touches far fewer rooms in the counter run below.
Thirty seconds: f equals g plus h
Save this file. It is the core of a_star.py without the arcade wrapper [2]:
from heapq import heappop, heappush
GRID = [
".............",
".###########.",
".#.........#.",
"S...~~~~~...T",
".#.........#.",
".###########.",
".............",
".............",
]
def find(ch):
for y, row in enumerate(GRID):
for x, cell in enumerate(row):
if cell == ch:
return (y, x)
raise ValueError(ch)
def neighbours(pos):
y, x = pos
for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
ny, nx = y + dy, x + dx
if 0 <= ny < len(GRID) and 0 <= nx < len(GRID[0]):
if GRID[ny][nx] != "#":
yield (ny, nx)
def step_cost(pos):
y, x = pos
return 5 if GRID[y][x] == "~" else 1
def manhattan(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def astar(start, goal):
came_from = {start: None}
g = {start: 0}
heap = [(manhattan(start, goal), 0, start)]
pops = 0
while heap:
f, spent, room = heappop(heap)
pops += 1
if spent > g[room]:
continue
if room == goal:
break
for nxt in neighbours(room):
new_g = spent + step_cost(nxt)
if nxt not in g or new_g < g[nxt]:
g[nxt] = new_g
came_from[nxt] = room
heappush(heap, (new_g + manhattan(nxt, goal), new_g, nxt))
path = []
cur = goal
while cur is not None:
path.append(cur)
cur = came_from[cur]
path.reverse()
return path, pops, len(g)
start, goal = find("S"), find("T")
path, pops, rooms = astar(start, goal)
cost = sum(step_cost(p) for p in path[1:])
print("path steps:", len(path) - 1)
print("path cost:", cost)
print("heap pops:", pops)
print("rooms with best g:", rooms)python3 astar_mini.pyCaptured output:
path steps: 14
path cost: 14
heap pops: 28
rooms with best g: 35Fourteen is the cheapest route on this grid: one floor step costs 1, mud ~ costs 5 [2][3]. The README line for level 11 says Dijkstra plus a distance guess, same cheapest path, fewer rooms explored [1]. Those two counters (heap pops and rooms with best g) are how you prove the heuristic saved work without changing the answer.
What the priority queue is doing
Dijkstra pops the smallest g, cost spent so far [3]. A star pops the smallest f = g + h, where h is Manhattan distance to T ignoring walls [2]. That pulls the frontier toward the treasure instead of expanding in cost rings.
Dijkstra ranks by g alone; A star adds h so the heap chases the goal while g still records true mud and floor cost.
Walk the diagram with numbers. Cell A spent 6 so far and still looks eight Manhattan steps from T, so f = 14. Cell B already spent 10, but sits only two Manhattan steps away, so f = 12. The heap pops B first even though B spent more. That is the whole trick: optimism about the remaining distance can outweigh a larger g, as long as h never overshoots the true leftover cost on this map.
The module docstring in a_star.py states the guess never exceeds real cost on this map, so the cheapest path stays correct [2]. If you inflate h, you can dequeue a shortcut that is not actually cheapest. Admissible means h(n) <= true remaining cost for every node. Consistent (monotone) heuristics also satisfy h(n) <= step_cost(n, m) + h(m) for every edge; Manhattan on four-neighbor unit grids is consistent when every open tile costs at least 1, and it stays admissible here when mud costs more than floor because the underestimate still ignores walls and mud [2].
Match the arcade sources on one dungeon
Comparing counters is easier with a short script beside a_star.py and dijkstra.py [2][3]:
git clone https://github.com/kamilikamil/algo-arcade.git
cd algo-arcade
python3 compare_heap.pyCreate compare_heap.py beside the levels:
from bfs import DUNGEON
from a_star import distance
from arcade import find, neighbours, step_cost
from heapq import heappop, heappush
def explore(use_heuristic):
start, goal = find(DUNGEON, "S"), find(DUNGEON, "T")
came_from = {start: None}
cost = {start: 0}
heap = (
[(distance(start, goal), 0, start)]
if use_heuristic
else [(0, start)]
)
pops = 0
while heap:
if use_heuristic:
_, spent, room = heappop(heap)
else:
spent, room = heappop(heap)
pops += 1
if spent > cost[room]:
continue
if room == goal:
break
for step in neighbours(DUNGEON, room):
new = spent + step_cost(DUNGEON, step)
if step not in cost or new < cost[step]:
cost[step] = new
came_from[step] = room
if use_heuristic:
heappush(heap, (new + distance(step, goal), new, step))
else:
heappush(heap, (new, step))
return pops, len(cost)
a_pops, a_rooms = explore(True)
d_pops, d_rooms = explore(False)
print("A* heap pops:", a_pops, "rooms:", a_rooms)
print("Dijkstra heap pops:", d_pops, "rooms:", d_rooms)Captured output:
A* heap pops: 28 rooms: 35
Dijkstra heap pops: 68 rooms: 71Same goal cost (14 per the mini script), but Dijkstra churns more heap work here [1][3]. For the animated map, run python3 a_star.py after clone [1][2].
Read those two pairs carefully. Dijkstra records a best g for 71 rooms and pops the heap 68 times. A star records 35 rooms and pops 28 times. The path cost is still 14 either way. Exploration count is not a different answer; it is a different amount of work to reach the same answer. On a larger open map the gap usually grows because Dijkstra keeps expanding low-cost rings in directions that never point at T.
Read the maze the way the level does
DUNGEON in bfs.py is an 8-row ASCII map shared by BFS, Dijkstra, and A star [1]. S starts on row 3, T on the right, ~ is mud, # is wall. Dijkstra walks around mud when mud costs more than floor [3]; BFS minimizes hops, which is why the README keeps these levels adjacent [1].
a_star.py imports that grid and only changes the heap ordering [2]. The if spent > cost[room]: continue guard is the same stale-heap trick both levels use [2][3]. When you port the idea to your own graph, keep that guard or stale heap entries will waste pops.
Why stale entries exist: Python's heapq has no decrease-key. When a better g appears for a room, the code pushes a new tuple and leaves the old one sitting in the heap. Later pops see a spent value larger than the recorded best and skip. Without that skip, you expand from outdated costs and the path can still recover, but the pop counter balloons.
Heuristic choices that change behavior
Manhattan distance fits four-neighbor grids: |dy| + |dx| [2]. Euclidean distance fits free movement with diagonals or continuous space. On this arcade map, Euclidean underestimates less sharply near walls that force a detour, and it can still be admissible, but the heap order will differ from the shipped distance() helper.
Set h = 0 for every node and the algorithm is Dijkstra. Set h to the true remaining cost and A star expands only along an optimal path (perfect information, rare in games). Inflate h above the true remaining cost and you may get a faster search that returns a non-optimal path. Game AIs sometimes accept that trade-off on purpose; interview answers usually must keep optimality, so stick to admissible heuristics unless the problem says otherwise.
Tie-breaking at equal f matters for determinism. Python compares the next tuple fields when f ties: here that is g, then the room coordinate if you encode it. Without an explicit tie key, two runs can expand different rooms in different orders while still agreeing on final cost. If your tests assert visit order, add a stable third key such as insertion counter.
Pitfalls that bite interviews and game AIs
-
Euclidean distance on a grid where diagonals are illegal. Manhattan lines up with the four-neighbor moves ALGO ARCADE uses [2].
-
Missing the stale-heap guard. Old larger
gvalues keep getting expanded and your "faster than Dijkstra" claim evaporates on the pop counter. -
Calling A star faster than Dijkstra without naming the heuristic. With h = 0, it is Dijkstra [2]. With a bad overestimate, it can be wrong.
-
Feeding BFS when costs differ: the shortest hop path plows through mud here and reports cost 32 while the heap methods report 14 [1][3].
-
Treating explored room counts as wall-clock proof. Heap levels quote
O((V + E) log V)[1][2]. Tiny maps still care about constants, and a noisy laptop timer is a weak substitute for the pop and room counters above. -
Stopping the first time you see the goal on the heap instead of when you pop it. With a consistent heuristic you can stop on pop; stopping on push can accept a suboptimal discovery when costs vary.
Worked contrast on one mud cell
Stand on the tile just left of the mud strip and look right. One hop into mud costs 5. Walking around on floor costs more steps but each step is 1. BFS takes the mud because hops are equal. Dijkstra and A star pay for mud in g, so they prefer the long floor path when its summed cost is lower [2][3]. The heuristic still points east toward T, which is why A star does not need to fill the whole western half of the map the way Dijkstra can.
That is also why the path "looks obvious" after the fact. Humans see the treasure and sketch a corridor. The algorithm only gets that intuition if you encode it as h. Without h, the computer has to prove the eastward bias by expanding rings. With an admissible h, the computer still proves optimality through g, but it spends fewer expansions on rooms that cannot beat the current best estimate.
Where to go in the series
Dijkstra drops the guess and shows why weighted grids need a heap [3]. BFS is the unweighted special case. DFS is the wrong tool for shortest path but the right one for cycle structure. The Dev explainers hub lists the rest.
Send this to the friend who calls A star magic because the path looks obvious on the map.

Keep this guide
Filed under Dev explainers
Questions about this guide
How do I run this A star algorithm Python level?
Run python3 a_star.py and python3 dijkstra.py from the repository folder.
Why does this A star algorithm explore fewer rooms?
On this dungeon, its Manhattan-distance estimate directs the search toward the treasure while retaining route cost.
Sources
- ALGO ARCADE READMEgithub.com
- ALGO ARCADE A star sourcegithub.com
- ALGO ARCADE Dijkstra sourcegithub.com