Sub topic 5
How A* Works Step by Step
This chapter assumes you can read Python and know what a priority queue does. It also assumes you have read the earlier chapters on uniform-cost search, greedy best-first search, and the evaluation function f(n) = g(n) + h(n). Here we follow the algorithm one step at a time on a small graph, so you can see what each data structure holds after each expansion. The next chapter covers heap implementation details. Later chapters prove why the result is optimal.
The State A* Keeps
A* maintains four pieces of state while it runs:
| Structure | Holds | Purpose |
|---|---|---|
| Open list | Nodes generated but not yet expanded, keyed by f | Decides which node to expand next |
| g table | Cheapest known cost from the start to each node | Supplies g(n) and detects better paths |
| Parent table | The predecessor on the cheapest known path | Rebuilds the path at the end |
| Closed set | Nodes already expanded | Stops the search from expanding a node twice |
Two words need to stay separate. A node is generated when A first reaches it as a neighbor and puts it on the open list. A node is expanded when A pops it from the open list and generates its neighbors. Most bugs in A* implementations come from mixing these two events up.
The Main Loop
The loop has only a few steps, but their order matters.
- Put the start node on the open list with g = 0 and f = h(start).
- Pop the node with the smallest f from the open list.
- If it is the goal, follow the parent pointers back to the start and return the path.
- If it is already closed, skip it, because it is a stale duplicate entry.
- Add it to the closed set.
- For each neighbor, compute newg = g(node) + cost(node, neighbor). If newg is lower than the neighbor's recorded g, record newg, set the parent, and push the neighbor with f = newg + h(neighbor).
- If the open list empties without reaching the goal, report that no path exists.
Step 6 is called relaxing an edge. A* uses the same rule as Dijkstra's algorithm. The only difference is the heap key, which adds h(neighbor) to the cost.
A Worked Example
Here is a small directed graph. The start is S and the goal is G.
The heuristic values are h(S) = 7, h(A) = 6, h(B) = 4, h(C) = 3, and h(G) = 0. None of them overestimates the true remaining cost. For example, the true cost from A is 7, along A→B→C→G. The heuristic also satisfies h(n) ≤ cost(n, m) + h(m) on every edge. That property is called consistency and gets its own chapter.
The program below runs A* on this graph and prints every event. It uses the same tie-breaking counter and lazy skipping of stale entries as the implementation in the next chapter.
import heapq
from itertools import count
graph = {
'S': [('A', 1), ('B', 4)],
'A': [('B', 2), ('G', 12)],
'B': [('C', 2)],
'C': [('G', 3)],
'G': [],
}
h = {'S': 7, 'A': 6, 'B': 4, 'C': 3, 'G': 0}
def astar_trace(start, goal):
tie = count()
open_heap = [(h[start], next(tie), start)]
g = {start: 0}
parent = {start: None}
closed = set()
step = 0
while open_heap:
f, _, node = heapq.heappop(open_heap)
if node in closed:
print(f" skip stale entry {node} (f={f})")
continue
step += 1
print(f"{step}. expand {node}: g={g[node]}, f={f}")
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], g[goal]
closed.add(node)
for nxt, cost in graph[node]:
new_g = g[node] + cost
if new_g < g.get(nxt, float('inf')):
old = g.get(nxt)
g[nxt] = new_g
parent[nxt] = node
heapq.heappush(open_heap, (new_g + h[nxt], next(tie), nxt))
note = "new" if old is None else f"improved from {old}"
print(f" {nxt}: g={new_g}, f={new_g + h[nxt]} ({note})")
return None, float('inf')
path, cost = astar_trace('S', 'G')
print(path, cost)Output:
1. expand S: g=0, f=7
A: g=1, f=7 (new)
B: g=4, f=8 (new)
2. expand A: g=1, f=7
B: g=3, f=7 (improved from 4)
G: g=13, f=13 (new)
3. expand B: g=3, f=7
C: g=5, f=8 (new)
skip stale entry B (f=8)
4. expand C: g=5, f=8
G: g=8, f=8 (improved from 13)
5. expand G: g=8, f=8
['S', 'A', 'B', 'C', 'G'] 8Reading the Trace
The table lists the open list right after each step. Entries marked "stale" are left in the heap but no longer match the g table.
| Step | Expanded | Open list after (node: f) | Closed |
|---|---|---|---|
| 0 | none | S:7 | none |
| 1 | S | A:7, B:8 | S |
| 2 | A | B:7, G:13, B:8 (stale) | S, A |
| 3 | B | C:8, G:13, B:8 (stale) | S, A, B |
| 4 | C (after skipping stale B) | G:8, G:13 (stale) | S, A, B, C |
| 5 | G, goal reached |
Three things in this trace show up in almost every A* run.
A better path to an open node. In step 1, B enters the open list with g = 4. In step 2, A finds a path to B that costs 1 + 2 = 3. A overwrites g(B) and parent(B) and pushes a new entry with f = 7. Python's heapq cannot lower a key that is already in the heap, so the old entry B:8 stays behind. When it reaches the top, after step 3, B is already closed, and the loop throws the entry away. This approach is called lazy deletion*.
The goal is generated early with a bad cost. G first appears in step 2 through the expensive edge A→G, with g = 13. If the code returned when it generated the goal, the answer would be 13. A returns only when the goal is expanded. By that point, every entry still on the open list has f ≥ 8, so no cheaper route can remain. In step 4, C finds g(G) = 8, and that is the path A returns.
f never decreases across expansions. The expanded f values are 7, 7, 7, 8, 8. With a consistent heuristic, the f values along the expansion order never go down. This is why a closed node never needs to be reopened. The heuristic's job shows up in the f values too: f(S) = 7 is a lower bound on the answer, and the bound rises toward the true cost 8 as the search learns more.
How A* Differs from Its Neighbors on This Graph
The same graph shows how A* relates to the two algorithms from the earlier chapters.
| Algorithm | Heap key | Expansions before returning | Cost returned |
|---|---|---|---|
| Uniform-cost search | g | S, A, B, C, G (5) | 8 |
| Greedy best-first | h | S, B, C, G (4) | 9 (S→B→C→G) |
| A* | g + h | S, A, B, C, G (5) | 8 |
Greedy best-first goes straight to B because h(B) = 4 is the smallest value. It never discovers that going through A first is cheaper. On a graph this small, A expands as many nodes as uniform-cost search. On large maps, h stops A from expanding nodes that point away from the goal, and that is where it saves work.
Edge Cases
- Start equals goal. The first pop finds the goal, and the path is just
[start]with cost 0. - Unreachable goal. The open list eventually empties and A reports failure. A has to expand every reachable node to prove that no path exists, so failure is the most expensive outcome. On infinite or very large graphs, set an expansion limit.
- Zero heuristic. With h(n) = 0 for every node, f = g, and A* behaves exactly like uniform-cost search.
- Inconsistent but admissible heuristic. A* can find a cheaper path to a node that is already closed. The loop above updates g but then skips the popped entry, which can lose the optimal path. To fix this, remove the node from the closed set when its g improves (called reopening), or use a consistent heuristic.
- Zero-cost edges. The algorithm still terminates, because a node's g only changes when it strictly decreases.
Common Errors
- Ordering the heap by h or by g alone. That turns A* into greedy best-first search or uniform-cost search.
- Leaving out the tie-breaking counter. When two f values are equal, Python then compares the nodes themselves, which raises
TypeErrorfor node types that cannot be compared. - Adding a node to the closed set when it is generated instead of when it is expanded. Its g can then never improve.
- Rebuilding the path from the first parent ever recorded instead of the latest one.
Exercise
In the example, change the cost of edge A→G from 12 to 6. Trace A. Which node is expanded at step 3, and what path and cost does A return?
Show answer
After S is expanded, the open list holds A:7 and B:8. Expanding A sets B to g=3, f=7 and G to g=7, f=7. The tie-breaking counter pushed B before G, so step 3 expands B, which generates C with g=5 and f=8. Step 4 pops G (f=7), which is the goal. A* returns S→A→G with cost 7, which beats S→A→B→C→G at cost 8.
Exercise
A colleague's A* returns as soon as it pushes the goal onto the open list. On the original example graph, what cost does it report, and why is that wrong?
Show answer
It reports 13 through S→A→G, because G is first generated at step 2 when A is expanded. That is wrong because the open list still holds B with f=7, which is a lower bound below 13. The optimal path S→A→B→C→G costs 8.
Exercise
Suppose h(B) were 0 instead of 4 and all other values stayed the same. Does this change the returned path? Does it change how many nodes are expanded?
Show answer
The path stays S→A→B→C→G with cost 8, because h=0 is still admissible and still consistent. The order changes, though. Expanding S gives A:7 and B:4, so B is expanded first with g=4 and generates C with g=6, f=9. Next A (f=7) is expanded and improves B to g=3, f=3. B is already closed, so this new entry is skipped when it is popped, and C keeps g=6. The search then expands C and returns a path of cost 9, which is wrong. The setting h(B)=0 makes h inconsistent on edge S→A (7 > 1 + 6 is false, but on A→B, 6 > 2 + 0 is true), so A needs reopening support to find the optimal cost 8. This shows why the closed set is only safe with a consistent heuristic.