Iterative deepening search
迭代加深搜索
Repeat bounded depth-first search to recover shallowest solutions, distinguish cutoff from failure, and account for repeated work.
iterative-deepeningSearch shallowly, restart, and allow one more step
DFS can spend a long time in a deep branch while a short solution waits elsewhere. BFS finds a shallowest solution but may store a huge frontier. Iterative deepening tries depth limits 0, 1, 2, and so on. Each pass is a fresh depth-first traversal constrained by its limit.
This repeats work deliberately. The advantage is that an unsuccessful pass rules out every shorter solution, while the next pass keeps depth-first working storage. The method is usually called IDDFS or DFID. It asks for the fewest edges; unequal edge costs require a different criterion. Korf’s 1985 analysis explicitly focuses its asymptotic claim on exponential tree search, not on every possible graph. Korf, sections 3–4
A stopped search needs more than one kind of answer
A depth-limited search should distinguish:
| Result | Meaning | What the outer loop should do |
|---|---|---|
| found | A goal was reached within the limit | Return its path |
| cutoff | Some eligible continuation was excluded by the limit | Try a greater limit |
| failure | All relevant continuations were exhausted without a goal | Stop: greater depth cannot help |
AIMA’s bounded routine and outer loop make this distinction explicit. Its boundary rule conservatively returns cutoff at any non-goal node with zero remaining depth. Our version checks whether a path-legal successor exists there, so an isolated leaf can report failure immediately. These conventions may use different numbers of passes while preserving their stated meaning. AIMA, depth-limited and iterative-deepening routines
Assume fixed finite adjacency sequences and a goal determined solely by the complete current state. Within a pass, we reject only vertices already on the current path. Removing a cycle from a route leaves a valid, no-longer route under these assumptions, so a shortest route can be chosen simple. Excluding such cycles therefore preserves a shallowest solution.
If that solution has depth , each pass below finds none, and the pass at explores the required simple path unless another depth- solution was already returned. The first returned solution is shallowest. With common positive edge cost, it is also cheapest. When edge costs differ, that last conclusion no longer follows.
On a finitely branching infinite search space, every finite-depth pass is finite, so a solution at finite depth is eventually reached by an uncapped version. If no solution exists, deeper passes may continue forever. Our runnable example imposes a cap and reports limit when that cap, rather than natural exhaustion, ends the search.
Keep the active path, not a permanent closed set
Consider S→A→X→G and S→X→G, exploring A first. At limit 2, the first visit to X has zero remaining depth. The later visit from S has one remaining step and can reach G. A global boolean “X was seen” would wrongly discard the useful visit, even if that set were cleared between passes.
The following complete program removes a vertex from active on backtracking. Adjacency values must be repeatable finite sequences: a one-use generator would be consumed by earlier passes. The counters record calls to visit, including boundary and goal visits, not just nodes whose successors were expanded.
def depth_limited(graph, start, goal, limit):
if type(limit) is not int or not 0 <= limit <= 200:
raise ValueError('limit must be an integer in [0,200]')
path, active = [start], {start}
visits = 0
def visit(u, remaining):
nonlocal visits
visits += 1
if u == goal:
return 'found', path.copy()
if remaining == 0:
extendable = any(v not in active for v in graph.get(u, ()))
return ('cutoff' if extendable else 'failure'), None
cut = False
for v in graph.get(u, ()):
if v in active:
continue
active.add(v)
path.append(v)
status, result = visit(v, remaining-1)
path.pop()
active.remove(v)
if status == 'found':
return status, result
cut = cut or status == 'cutoff'
return ('cutoff' if cut else 'failure'), None
status, result = visit(start, limit)
return status, result, visits
def iterative_deepening(graph, start, goal, max_depth=40):
if type(max_depth) is not int or not 0 <= max_depth <= 200:
raise ValueError('max_depth must be an integer in [0,200]')
trace = []
for limit in range(max_depth+1):
status, path, visits = depth_limited(graph, start, goal, limit)
trace.append((limit, visits, status))
if status != 'cutoff':
return status, path, trace
return 'limit', None, trace
graph = {'S': ['A', 'X'], 'A': ['X'], 'X': ['G'], 'G': []}
status, path, trace = iterative_deepening(graph, 'S', 'G', 2)
assert status == 'found' and path == ['S', 'X', 'G']
assert trace == [(0, 1, 'cutoff'), (1, 3, 'cutoff'), (2, 5, 'found')]
assert iterative_deepening(graph, 'S', 'G', 1)[0] == 'limit'
assert iterative_deepening({'S': ['S']}, 'S', 'G', 4)[0] == 'failure'
assert iterative_deepening({}, None, None, 0)[1] == [None]
assert depth_limited({}, 'S', 'G', 0)[0] == 'failure'
print(status, path, trace)
The three passes make 1, 3 and 5 visits. The final path is S–X–G. In its last pass the algorithm first reaches X through A, backs out at the depth boundary, then revisits X through the shorter route. This is exactly the revisit a global boolean set would suppress.
The implementation caps depth at 200 to keep a recursive teaching example modest. It assumes a normal Python recursion limit with room for these frames; a process configured with a smaller limit can still raise RecursionError. Larger searches should use explicit frames and appropriate resource controls. limit means “not decided within the configured budget,” not “no solution.”
Repeated work can be cheap—or very expensive
For a complete -ary tree and exhaustive passes at limits 0 through , counting every visited node, depth- nodes are visited times. Thus
For fixed , factor out and put :
So the worst-case tree work stays under these conventions. A single exhaustive breadth-first pass through the same depth visits nodes. Their ratio approaches as grows. This is an asymptotic tree comparison, not a promise about the wall-clock time of an arbitrary task. Korf, section 4
| Tree | Single exhaustive pass | All limits |
|---|---|---|
| 15 | 26 | |
| 1111 | 1234 | |
| 4 | 10 |
A chain is the revealing exception. For , , so repeating the prefixes costs against a single traversal’s . The exponential-tree argument cannot be used after its assumption disappears.
Graphs can be worse. Many paths may merge into the same vertices. Our active-path set removes cycles but does not merge such alternative histories, so it may explore exponentially many paths in a graph with relatively few vertices. BFS with a global visited set can be much cheaper there. A global table can reduce repeated work, but its entries need a valid depth or cost dominance argument and consume additional memory. A bare visited flag is insufficient for bounded search. Poole and Mackworth, search-space pruning
The recursive code stores active vertices and frames, plus an trace across completed passes, assuming constant-size adjacency iterators and expected constant-time hashing. The explicitly supplied graph is excluded. A variant that materializes all siblings at every depth can require traversal storage instead. Successor generation, hashing complex states and copying a final route also have costs; the node-count model does not make them free.
Decide whether to deepen or stop
- At limit zero, the start is the goal. Which result is correct? Answer: found, with a one-vertex path. The goal check precedes the cutoff test.
- At limit zero, the start is a non-goal with no outgoing edges. What does this implementation return? Answer: failure. There is no eligible continuation for a larger limit to reveal.
- In the S–A–X example, why must X be revisited from S? Answer: the second route leaves one more step available. State identity alone does not describe the remaining search budget.
- A run stops at
max_depth=1with cutoff still present. Can it report “unreachable”? Answer: no. It returns limit. The example has a two-edge solution that the budget excludes.
Keep solution quality and resource claims conditional
Try a complete binary tree, a chain and a layered graph with merging routes. Measure total visits, distinct vertices and peak active depth separately. These quantities expose where repeated prefixes or duplicate paths dominate. Also compare the last completed pass with the total of every pass; reporting only the last pass hides part of the work.
Korf’s paper acknowledges earlier uses and rediscoveries and goes on to study heuristic thresholds. Its title should not be used to assert that all iterative search is always optimal in every resource. For weighted heuristic search, follow the IDA* topic; it is a separate treatment, not another name for the depth-limited algorithm here. The practical choice depends on branching, repeated states, acceptable path cost and the memory you can actually retain.
Make a prediction, then check
If cutoff remains when max_depth is reached,can the result be called unsolvable?
Learning objectives
- Distinguish found,cutoff,failure and budget limit,and explain revisits through remaining-depth counterexamples.
- Derive repeated-visit counts,compare exponential trees,chains and merging graphs,and state when shallowest means cheapest.
Prerequisites & connections
Explore related knowledge →References
- AIMA Python — search algorithms (commit f104e03, 2026-06-30)
AIMA Python contributors · 2026 - Depth-First Iterative-Deepening: An Optimal Admissible Tree Search
Richard E. Korf · 1985 - Artificial Intelligence: Foundations of Computational Agents,3rd edition —3.7 Pruning the Search Space
David L. Poole; Alan K. Mackworth
Version2 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: inspected fixed source code and course/paper material,independent graph-distance comparison,executed full programs and bilingual rereading; no independent human peer review.
- Reread bilingual result/budget distinctions,revisit example and four answers; independently derived W/B counts,geometric bound and quadratic work at b=1.
- Executed5 search checks:all4096 four-vertex directed graphs with self-loops against Floyd–Warshall distances;depth budget/revisit case,four full-tree counts,5000-level explicit stack and input boundaries.All93 site article programs executed successfully.
- Targeted follow-up check:IDA* article now exists;removed planned label and linked both locale articles,version2.Equations,code and remaining arguments retained byte-for-byte;existing search tests rerun successfully.
Source locations checked:
- AIMA Python — search algorithms (commit f104e03, 2026-06-30) · Fixed-commit lines335–363:goal precedes limit test,cutoff versus None,outer loop deepens only on cutoff. Article explicitly differs by checking path-legal boundary successors and by returning budget limit.
- Depth-First Iterative-Deepening: An Optimal Admissible Tree Search · Read original97–101(PDF1–5),especially§3 path/node branching distinction and§4 asymptotic exponential-tree claim and counting. Article includes root at limit0,independently derives its own visited-node convention,chain exception and tree ratios.
- Artificial Intelligence: Foundations of Computational Agents,3rd edition —3.7 Pruning the Search Space · Read§3.7.1–3.7.3,cycle checking via current-path set,multiple-path storage tradeoff and stated finite-branching conditions. No wholesale P-versus-NP assertion imported into explicit graph complexity.
Related topics