Sub topic 12
Tie-Breaking and Its Effect on Performance
This chapter assumes you have read the earlier chapters on the A* implementation with a binary heap and on consistent heuristics. You should be comfortable with Python's heapq module and with how tuples are compared element by element.
A always pops the node with the smallest f = g + h. That rule says nothing about what happens when several nodes share the smallest f. On many real maps this is the usual case. The order you choose among them does not change the cost of the path A returns, but it can change the number of nodes expanded by an order of magnitude.
Why Ties Are So Common
Take an empty 4-connected grid with unit step costs and the Manhattan heuristic. Put the start at (0, 0) and the goal at (19, 19). Every cell inside the bounding box of start and goal lies on some shortest path. So for every such cell, g (its distance from the start) plus h (its Manhattan distance to the goal) equals 38, the optimal cost.
That puts 400 cells on the same f-value. A* has to pick among them, and the heap's secondary key decides which one comes out first.
This follows from a general property of A with a consistent heuristic. Let C be the optimal cost:
| Node's f-value | Does A* expand it? |
|---|---|
| f < C* | Always, whatever the tie-breaking |
| f = C* | Sometimes. Tie-breaking decides how many |
| f > C* | Never |
Tie-breaking only affects the f = C* layer. On open grids that layer can contain most of the map, so it matters a great deal there.
What the Tie-Breaker Actually Is
In the heap-based implementation from the earlier chapter, entries look like (f, counter, node). The counter comes from itertools.count() and grows with every push. When two entries have equal f, the one with the smaller counter wins, so equal-f nodes come out first-in, first-out (FIFO).
FIFO is the worst sensible choice on open grids. Among equal-f nodes it behaves like breadth-first search, finishing every cell at distance k from the start before moving to distance k + 1. The goal is the farthest cell, so it gets popped close to last.
Common Policies
| Policy | Heap key | Behaviour among equal f |
|---|---|---|
| FIFO | `(f, counter)` | Breadth-like. Expands the whole equal-f layer near the start first |
| LIFO | `(f, -counter)` | Depth-like. Follows the most recent branch |
| Prefer low h | `(f, h, counter)` | Pushes toward the goal |
| Prefer high g | `(f, -g, counter)` | Same as low h, because g = f − h when f is fixed |
| Heuristic nudge | `(g + h*(1+ε), counter)` | Folds the tie-break into f itself |
Preferring low h (or high g) is the standard recommendation. Among nodes that look equally good overall, it picks the one with the most confirmed progress. On the empty grid it walks almost straight to the goal.
Measuring the Difference
The following program runs A* with each policy and counts expansions. It is self-contained, so you can run it as shown.
import heapq
from itertools import count
def astar_count(start, goal, neighbors, h, tie="fifo"):
counter = count()
def key(g_val, h_val):
n = next(counter)
f = g_val + h_val
if tie == "fifo":
return (f, n)
if tie == "lifo":
return (f, -n)
if tie == "low_h":
return (f, h_val, n)
raise ValueError(tie)
open_heap = [(key(0, h(start)), start)]
g = {start: 0}
closed = set()
while open_heap:
_, node = heapq.heappop(open_heap)
if node == goal:
return g[goal], len(closed)
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
heapq.heappush(open_heap, (key(new_g, h(nxt)), nxt))
return float("inf"), len(closed)
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])
size = 20
grid = ["." * size for _ in range(size)]
start, goal = (0, 0), (size - 1, size - 1)
nb = grid_neighbors(grid)
h = lambda n: manhattan(n, goal)
for policy in ("fifo", "lifo", "low_h"):
cost, expanded = astar_count(start, goal, nb, h, policy)
print(f"{policy:6s} cost={cost} expanded={expanded}")All three policies report cost 38. FIFO expands close to all 400 cells, and low_h expands only the cells along one path, a few dozen. The path cost stays the same while the work drops by roughly a factor of ten. On a 200 × 200 open map the gap grows to about 40,000 expansions against about 400.
LIFO also does well on this empty grid, but don't rely on it. Depth-like ordering commits to whichever branch was pushed last. With obstacles, that branch can lead into a pocket that has to be fully explored before A* backs out. Prefer low h is the more predictable choice.
Obstacles Reduce the Benefit
Once walls are added, many cells are no longer on any shortest path. Their f rises above C, and A never expands them under any policy. The f = C* layer shrinks, so tie-breaking matters less. On mazes with narrow corridors, every policy expands about the same set of nodes. Tie-breaking pays off most on wide-open terrain and on maps with large open regions between obstacles.
The Heuristic Nudge
Some implementations skip the secondary key and scale h slightly:
def nudged(h, expected_max_cost):
p = 1.0 / expected_max_cost
return lambda n: h(n) * (1.0 + p)Multiplying by (1 + p) makes nodes with smaller h win among those with the same g + h. This is the same idea as the low-h policy, applied through f. The trade-off is that the scaled heuristic is no longer strictly admissible. If p is less than 1 divided by the longest path cost you expect, the error stays under one unit step. With integer costs, the returned path is then still optimal in practice. In general, this is weighted A with a weight very close to 1, which the chapter on weighted A covers. A secondary key gives the same benefit without touching optimality, so prefer it when your heap supports compound keys.
Floating-Point Near-Ties
With octile or Euclidean heuristics on 8-connected grids, f values are irrational sums like 7 + 3√2. Two paths that are mathematically equal can differ in the last bit depending on the order of additions. Those near-ties are broken by rounding noise, not by your policy, and the expansion order becomes erratic. Two fixes are common:
- Scale costs to integers, for example straight = 10 and diagonal = 14. This is slightly inadmissible for diagonals, because 14 > 10√2, so check whether exact optimality matters to you.
- Round f to a fixed number of decimals inside the heap key, keeping the exact g in the
gdictionary.
Path Shape Versus Node Count
On grids, many different paths share the optimal cost. Tie-breaking decides which one you get. Low-h ordering on a 4-connected grid tends to produce an "L" shape: all the moves along one axis, then all the moves along the other. Games often want paths that look straighter. A well-known trick adds a small penalty based on the cross product between the vector from the current cell to the goal and the vector from the start to the goal. That penalty favours cells near the straight line from start to goal. It changes how the path looks, not its cost, and it is a different goal from reducing expansions. Decide which of the two you are tuning for.
Correctness Is Never at Stake
Every policy that only reorders entries with equal f keeps all of A*'s guarantees. The optimality proof from the earlier chapter only uses the fact that nodes come out in non-decreasing f. It never says which equal-f node comes first. Only the heuristic nudge, which changes f itself, needs the extra care described above.
Exercise
On an empty 4-connected grid with Manhattan distance, the start is at (0, 0) and the goal at (9, 4). Roughly how many nodes does A* expand with FIFO tie-breaking, and roughly how many with "prefer low h"? Explain why.
Show answer
Every cell in the 10 × 5 bounding box lies on a shortest path, so all 50 cells have f = 13. FIFO handles them in breadth-like order and reaches the goal last, expanding close to 50 nodes. "Prefer low h" always picks the frontier cell nearest the goal, so it walks one shortest path and expands about 13 or 14 nodes.
Exercise
A colleague changes the heap key from (f, h, counter) to (f, h, node) to save memory. On a grid with (row, col) tuples the code still works. What risk does this introduce, and when does it fail outright?
Show answer
When f and h both tie, Python compares the nodes. With tuple coordinates this quietly imposes a lexicographic preference that biases path shape and expansion order. With node types that do not define ordering, such as plain objects or dicts, heapq raises TypeError on the first full tie. The counter guarantees the comparison never reaches the node.
Exercise
Why does tie-breaking matter less on a maze with narrow one-cell corridors than on an open field?
Show answer
In a maze, most cells are not on any optimal path, so their f is greater than C and A never expands them under any policy. Only the nodes with f = C* depend on tie-breaking, and in a maze that set is small, close to the optimal path itself.