IDA* and memory-bounded search
IDA* 与内存受限搜索
Replace a large best-first frontier with repeated f-bounded traversals; prove optimality under admissibility and count every stored object.
ida-starKeep a cost threshold instead of a giant queue
A* orders its frontier by : cost already paid plus an estimated remaining cost. On a large problem, storing that frontier can be the bottleneck. IDA* uses the same evaluation but performs a depth-first traversal, cutting off any branch whose exceeds a threshold. If no solution is found, it starts over with a larger threshold.
The threshold does not increase by an arbitrary fixed step. It becomes the smallest exceeded value encountered in the previous pass. Richard Korf’s 1985 paper introduces this heuristic extension after discussing depth-based iterative deepening. Our integer-cost example follows that rule; it is not a reproduction of the paper’s puzzle experiments. Korf, section 6
Why the thresholds do not jump over an optimal solution
Let be the cheapest route cost, the cost of the current path to node , and a nonnegative estimate with . An admissible heuristic never exceeds the actual cheapest remaining cost. Start with threshold . A pass follows only branches with , and returns the minimum exceeded score if it finds no goal:
Here is the set of nodes cut off in pass . Assume a finite graph with positive edge costs and complete state descriptions. An optimal path can be chosen simple. Along that path, admissibility gives . Initially . If a pass with finds no goal, the first excluded node on the optimal path has an exceeded score no greater than . The next threshold, being the minimum over all exceeded scores, is no greater either.
When a goal is accepted, the bound check has already established . Because , the returned cost is at most . It cannot be below the global optimum, so it equals . This reasoning does not require consistency; it relies on admissibility and on retaining all path alternatives needed by the depth-first passes. Korf explains how consistency simplifies the presentation, rather than making it an essential restriction on the basic result. Korf, section 6, pages 103–104
The finite graph and active-path cycle check make each pass finite. More generally, finite branching, nonnegative and an edge-cost lower bound bound the depth admitted under a finite threshold. An infinite zero-cost chain would defeat that argument. Termination of uncapped search and stopping at a chosen resource budget are different promises.
Check the bound before accepting a goal
This complete teaching program uses positive integer edge costs and nonnegative integer heuristics. Missing heuristic entries mean zero. It validates the supplied finite, repeatable adjacency sequences, but does not prove that the heuristic is admissible. A caller who overestimates remaining cost has left the optimality contract.
The active set contains only the current path. A state may be revisited through another route with a different value. A global boolean closed set would incorrectly treat those situations as interchangeable. The contour checks its bound before its goal test, and the outer loop distinguishes natural failure from a pass-budget limit. AIMA, fixed-commit IDA* routine
from math import inf
def ida_star(graph, start, goal, h=None, max_passes=100):
# Edges are (neighbor, positive_integer_cost), stored in repeatable sequences.
h = {} if h is None else h
if type(max_passes) is not int or max_passes < 1:
raise ValueError('max_passes must be a positive integer')
def heuristic(v):
value = h.get(v, 0)
if type(value) is not int or value < 0:
raise ValueError('heuristics must be nonnegative integers')
return value
bound = heuristic(start)
if heuristic(goal) != 0:
raise ValueError('goal heuristic must be zero')
for u, edges in graph.items():
heuristic(u)
for v, cost in edges:
if type(cost) is not int or cost <= 0:
raise ValueError('edge costs must be positive integers')
heuristic(v)
path, active, thresholds = [start], {start}, []
def contour(u, cost, threshold):
score = cost + heuristic(u)
if score > threshold:
return score, None
if u == goal:
return cost, path.copy()
next_bound = inf
for v, weight in graph.get(u, ()):
if v in active:
continue
path.append(v)
active.add(v)
value, route = contour(v, cost+weight, threshold)
active.remove(v)
path.pop()
if route is not None:
return value, route
next_bound = min(next_bound, value)
return next_bound, None
for _ in range(max_passes):
thresholds.append(bound)
value, route = contour(start, 0, bound)
if route is not None:
return {'status': 'found', 'cost': value, 'path': route, 'thresholds': thresholds}
if value == inf:
return {'status': 'failure', 'cost': None, 'path': None, 'thresholds': thresholds}
bound = value
return {'status': 'limit', 'cost': None, 'path': None, 'thresholds': thresholds}
graph = {'S': [('A', 3), ('B', 1)], 'A': [('G', 2)],
'B': [('A', 1)], 'G': []}
result = ida_star(graph, 'S', 'G', {'S': 2, 'A': 1, 'B': 1})
assert result['cost'] == 4 and result['path'] == ['S', 'B', 'A', 'G']
assert result['thresholds'] == [2, 3, 4]
assert ida_star(graph, 'S', 'G', max_passes=1)['status'] == 'limit'
assert ida_star({'S': [('S', 1)]}, 'S', 'G')['status'] == 'failure'
assert ida_star({}, None, None)['path'] == [None]
# Admissible but inconsistent: f decreases on S -> A, yet the optimal path is found.
assert ida_star(graph, 'S', 'G', {'S': 4, 'B': 3})['cost'] == 4
print(result)
The sample has edges S→A costing 3, S→B costing 1, B→A costing 1 and A→G costing 2. Its heuristic is . These estimates are admissible and consistent, but deliberately weak.
| What prevents an earlier answer? | Outcome | |
|---|---|---|
| 2 | Direct A has ; A reached through B has | Next threshold 3 |
| 3 | The cheaper route reaches G with | Next threshold 4 |
| 4 | The direct-A route reaches G with and is rejected | Return S–B–A–G, cost 4 |
The first route reaching the goal in a depth-first traversal need not be accepted: an over-bound goal must be rejected. Threshold 4 is sufficient for the cheaper route, even though the direct-A branch is explored first.
The final assertion uses . This is still admissible, but inconsistent on S→A because . The algorithm revisits A via B and returns cost 4. Admissible does not mean that every path’s value increases monotonically.
Low frontier storage does not make repeated work disappear
At a given time the search retains an active path and recursion frames. With constant-size adjacency iterators, that working storage is for maximum active depth . This implementation also saves all thresholds, so its additional search storage is , excluding the supplied graph and heuristic mapping. Upfront validation scans the graph in time without making a reverse index or a full visited set. The recursive implementation is still subject to Python’s recursion limit on deep paths.
A* often avoids repeated expansion by retaining more information. IDA* may rediscover the same state on many paths and in many passes. If a tree has many similarly sized contours or a chain has gradually increasing scores, the accumulated work can far exceed that of one best-first traversal. For a unit-cost chain and , thresholds 0 through repeatedly inspect its prefixes, giving quadratic rather than linear work in . Korf’s tree efficiency results have explicit growth and heuristic assumptions; they are not a universal equivalence between A* and IDA* runtimes.
Dense floating-point scores can create many threshold values and awkward equality boundaries. The integer restriction here keeps the example exact; it is not a claim that IDA* only applies to integers. Changing the arithmetic representation requires a clear comparison policy and renewed correctness checks, not a hidden tolerance that lets over-bound goals pass.
Bad heuristics can return bad answers even when their values look well formed. For S→A→G with costs 3 and 3, and S→B→G with costs 2 and 2, setting and all other estimates to zero can make the code return the cost-6 route before the cost-4 route is explored. Input validation catches types and signs; it cannot certify the needed upper bound on estimates.
A transposition table may reduce repeated work but must retain enough cost, bound and search-context information to justify pruning. It uses additional memory and is not equivalent to adding a bare seen set. Other memory-limited searches preserve selected frontier information instead of restarting whole contours; this article’s code and guarantees concern IDA*. Poole and Mackworth, cycle versus multiple-path pruning
Decide which contract is being used
- At threshold 4, the first route reaches G with cost 5. May the program return it? Answer: no. The bound check must precede acceptance; the sample has a cost-4 route still to explore.
- Must an admissible heuristic be consistent for this path-search version’s cost proof? Answer: no. The proof follows the surviving optimal path and bounds the next threshold; the sample includes an inconsistent admissible case.
- Does a nonnegative integer heuristic with zero at G necessarily satisfy admissibility? Answer: no. An intermediate value can exceed the actual remaining cost, as the counterexample shows.
- The configured pass count is exhausted while a finite next threshold exists. Is the problem unsolvable? Answer: not established. The return status is limit; a later contour may contain a solution.
Measure a whole run, not just its final contour
Record thresholds, total calls, repeated states, maximum active depth and retained auxiliary records. Compare a chain, a branching tree and a graph with many merging routes. When comparing with A*, use the same edge costs, heuristic, tie rules where applicable and goal semantics; count any validation or preprocessing consistently.
The sample tests can be extended by generating small positive-weight graphs, computing exact remaining costs independently, then choosing admissible estimates below those costs. Compare returned route costs with an independent shortest-path solver, including inconsistent estimates and no-path cases. The A* article explains best-first search, while iterative deepening isolates the depth-budget idea. Combining the two requires the threshold and pruning conditions established here; it does not preserve every implementation shortcut from either one.
Make a prediction, then check
With threshold4,a route reaches the goal at cost5.What should happen?
Learning objectives
- Use the admissible optimal path to bound thresholds by C* and explain goal-check order versus consistency.
- Calculate contour thresholds and route cost while accounting for paths,threshold history,repeated states and budget status.
Prerequisites & connections
Explore related knowledge →References
- Depth-First Iterative-Deepening: An Optimal Admissible Tree Search
Richard E. Korf · 1985 - AIMA Python — search algorithms (commit f104e03, 2026-06-30)
AIMA Python contributors · 2026 - Artificial Intelligence: Foundations of Computational Agents,3rd edition —3.7 Pruning the Search Space
David L. Poole; Alan K. Mackworth
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check:source locations,independent shortest-distance comparison,executed counterexamples and full bilingual rereading;no independent human peer review.
- Full bilingual rereading:admissible-inconsistent case,[2,3,4] thresholds,inadmissible6-versus4 counterexample,recursion and O(d+P) storage,integer and budget contracts.
- Seven new checks executed successfully:4096 four-vertex directed graphs,729 three-vertex weighted graphs,40 random six-vertex graphs,thresholds and invalid heuristics,predecessor illustration,premature-meeting counterexample and boundaries.Search suite totals12 checks;95 article programs executed.
- Mobile inspection found the two-character heading wrapping vertically;both locales now use the already-defined threshold symbol T.Table values and algorithm are unchanged.
Source locations checked:
- Depth-First Iterative-Deepening: An Optimal Admissible Tree Search · Read original103–105,section6:minimum exceeded f threshold,admissibility,consistency as simplifying presentation,pathmax and explicitly conditioned Theorem6.4. Own proof tracks an optimal simple path without claiming universal time equivalence.
- AIMA Python — search algorithms (commit f104e03, 2026-06-30) · Read pinned lines476–513:bound-before-goal test,minimum exceeded value,active-path cycle exclusion,repeated contours. Own integer-cost validation,status/threshold trace and O(d+P) accounting are distinct additions.
- Artificial Intelligence: Foundations of Computational Agents,3rd edition —3.7 Pruning the Search Space · Previously inspected§3.7.1–3.7.3 current-path versus multiple-path pruning;used to explain why a boolean global seen set does not establish cost dominance for IDA*.
Related topics