Sub topic 15
IDA*: A* with Linear Memory
This chapter assumes you already know the A loop from earlier chapters: the open list ordered by f = g + h, the closed set, and the admissibility conditions that make A optimal. You should also be comfortable with recursive depth-first search (DFS) in Python.
A has a practical weakness. It keeps every generated node in memory, in the open heap, the g table, and the parent table. On large state spaces, such as the 15-puzzle (about 10^13 states) or high-resolution maps, memory runs out long before time does. Iterative deepening A (IDA) solves this by giving up A's memory and repeating work instead.
The Core Idea: Depth-First Search with an f-Bound
IDA* combines two ideas:
- Iterative deepening: run DFS repeatedly, each time with a larger cutoff.
- The A* evaluation function: the cutoff is measured in f = g + h, not in depth.
Each iteration is a plain DFS that prunes any node whose f exceeds the current bound. When an iteration fails, the next bound is the smallest f-value that went over the old bound. The first bound is h(start).
The only state the search holds is the current path from the start. Memory is therefore O(d), where d is the length of the solution path. A* needs O(b^d) memory in the worst case, where b is the branching factor.
Why the Next Bound Is the Minimum Overflow
Choosing the smallest exceeding f-value is what keeps IDA optimal. Suppose h is admissible, and say the current bound B failed. Every path with f ≤ B has been explored, and none reached the goal. The cheapest unexplored node has f = B', the minimum overflow. No solution can cost less than B', because every node on an optimal path has f ≤ C when h is admissible. Raising the bound to exactly B' means IDA never skips past the optimal cost C. When it does find the goal, g(goal) ≤ bound ≤ C*, so the path is optimal.
IDA expands nodes in roughly the same f-order as A, iteration by iteration. It only needs admissibility, not consistency. Since it keeps no closed set, it never has to decide whether to reopen a node.
A Runnable, Instrumented Implementation
The version below follows the tutorial's ida_star but makes three additions. It keeps a set alongside the path so cycle checks run in O(1). It returns the solution cost. It records the bound and the number of nodes expanded in each iteration.
FOUND = object()
def ida_star_traced(start, goal, neighbors, h):
path = [start]
on_path = {start}
expanded = []
found_cost = [None]
def search(g, bound):
node = path[-1]
f = g + h(node)
if f > bound:
return f
expanded[-1] += 1
if node == goal:
found_cost[0] = g
return FOUND
minimum = float('inf')
for nxt, cost in neighbors(node):
if nxt in on_path:
continue
path.append(nxt)
on_path.add(nxt)
t = search(g + cost, bound)
if t is FOUND:
return FOUND
minimum = min(minimum, t)
path.pop()
on_path.discard(nxt)
return minimum
bound = h(start)
bounds = []
while True:
bounds.append(bound)
expanded.append(0)
t = search(0, bound)
if t is FOUND:
return list(path), found_cost[0], list(zip(bounds, expanded))
if t == float('inf'):
return None, float('inf'), list(zip(bounds, expanded))
bound = t
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 = [".....",
".###.",
"....."]
start, goal = (1, 0), (1, 4)
path, cost, trace = ida_star_traced(start, goal, grid_neighbors(grid),
lambda n: manhattan(n, goal))
print(cost) # 6
print(trace) # [(4, 1), (6, 7)]
print(path)Here is the trace. The first bound is h(start) = 4. Both open neighbors of the start have f = 6, so the first iteration expands only the start and reports 6 as the next bound. The bound skips 5 because every unit move on this grid changes Manhattan distance by exactly ±1, so f always changes in steps of 0 or 2. The second iteration finds a path of cost 6 along the bottom row.
Trade-offs Against A*
| Aspect | A* | IDA* |
|---|---|---|
| Memory | O(nodes generated) | O(solution depth) |
| Duplicate detection | Yes, through the g table and closed set | Only cycles on the current path |
| Re-expansion | None with a consistent h | Every earlier iteration is repeated |
| Heuristic requirement for optimality | Admissible (consistent avoids reopening) | Admissible |
| Per-node overhead | Heap push/pop, O(log n) | Recursion only, very cheap |
| Best fit | Graphs with many transpositions that fit in RAM | Huge, tree-like spaces with integer costs |
When Repetition Is Cheap
The cost of repeating earlier iterations depends on how fast the f-contours grow. If each new bound admits about b times more nodes than the last, the final iteration dominates the total. The overhead is then a constant factor of roughly b/(b−1). This is the same argument that makes iterative-deepening DFS nearly as fast as BFS. On the 15-puzzle with Manhattan distance, this holds and IDA* works very well.
Failure Modes
Many Distinct f-Values
The good case needs the bound to rise in large, discrete steps. With real-valued edge costs, such as octile grids with √2 diagonals or road networks, almost every node may have a unique f-value. Each iteration might then admit only one new node, and the total work grows from N to O(N²). Common fixes:
- Round or scale costs to integers. This changes the optimality guarantee to "optimal for the rounded costs."
- Raise the bound by a fixed increment δ or a percentage. The returned solution is then within δ of optimal, because the final iteration may overshoot C* by up to δ.
Transposition-Heavy Graphs
On an open grid, the number of distinct paths to a cell grows exponentially with distance, even though the number of cells grows only quadratically. Plain IDA can be exponentially slower than A here. If memory allows, add a transposition table: a bounded dictionary from state to the best g seen, used to prune revisits with g ≥ the stored value. This moves IDA back toward A while keeping memory under your control.
Undetected Unsolvability
On an infinite or very large space with no solution, IDA* may never terminate, because some node always exceeds the bound. The float('inf') check only fires when the reachable space is finite and fully explored. Add an explicit bound limit if you need a guaranteed stop.
Practical Enhancements
- Parent pruning: in puzzles, skip the move that undoes the previous one. It is cheaper than a full path-membership check and removes most cycles.
- Move ordering: within an iteration, try successors with lower h first. This does not reduce the work of earlier iterations, but it shortens the final one, where the search stops as soon as it reaches the goal.
- Incremental heuristics: compute h(child) from h(parent) and the move. For Manhattan distance on tile puzzles, only one tile changes, so the update is O(1).
- Alternatives: recursive best-first search (RBFS) and SMA* also use limited memory. They do less re-expansion, at the cost of more complex code.
Exercise
Run IDA* with h = 0 on a graph with unit edge costs. What does each iteration correspond to, and what is the sequence of bounds?
Show answer
With h = 0, f equals g, which here is depth. Each iteration is a depth-limited DFS, and the bounds go 0, 1, 2, ... up to the solution depth. IDA* reduces to iterative-deepening DFS.
Exercise
On an 8-connected grid where diagonal moves cost sqrt(2), you replace A with IDA using the octile heuristic, and it becomes far slower even on small maps. Give two reasons and one fix for each.
Show answer
First, f-values are irrational sums of 1 and sqrt(2), so nearly every node has a distinct f and each iteration adds very few nodes, making total work close to quadratic. Fix: raise the bound by a fixed increment or scale and round costs to integers, accepting bounded suboptimality. Second, grids have many transpositions, and IDA re-explores every distinct path to a cell. Fix: add a transposition table of best g per cell, or use A if the map fits in memory.
Exercise
Why does IDA* stay optimal with an admissible but inconsistent heuristic, without any node-reopening logic?
Show answer
IDA keeps no closed set, so it never commits to a node's g-value. Every path is evaluated fresh in each iteration. Admissibility ensures every node on an optimal path has f at most C, so the bound never skips past C. The goal is first reached in an iteration whose bound is at most C, which gives an optimal cost.