AI Wiki中文/EN

Iterative deepening search

迭代加深搜索

Repeat bounded depth-first search to recover shallowest solutions, distinguish cutoff from failure, and account for repeated work.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Search 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:

ResultMeaningWhat the outer loop should do
foundA goal was reached within the limitReturn its path
cutoffSome eligible continuation was excluded by the limitTry a greater limit
failureAll relevant continuations were exhausted without a goalStop: 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 dd, each pass below dd finds none, and the pass at dd explores the required simple path unless another depth-dd 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 bb-ary tree and exhaustive passes at limits 0 through dd, counting every visited node, depth-ii nodes are visited d−i+1d-i+1 times. Thus

W(b,d)=∑i=0d(d−i+1)bi.W(b,d)=\sum_{i=0}^{d}(d-i+1)b^i.

For fixed b>1b>1, factor out bdb^d and put j=d−ij=d-i:

W(b,d)=bd∑j=0d(j+1)b−j<bd(1−1/b)2.W(b,d)=b^d\sum_{j=0}^{d}(j+1)b^{-j}<\frac{b^d}{(1-1/b)^2}.

So the worst-case tree work stays O(bd)O(b^d) under these conventions. A single exhaustive breadth-first pass through the same depth visits B(b,d)=∑i=0dbiB(b,d)=\sum_{i=0}^d b^i nodes. Their ratio approaches b/(b−1)b/(b-1) as dd grows. This is an asymptotic tree comparison, not a promise about the wall-clock time of an arbitrary task. Korf, section 4

TreeSingle exhaustive pass BBAll limits WW
b=2,d=3b=2,d=31526
b=10,d=3b=10,d=311111234
b=1,d=3b=1,d=3410

A chain is the revealing exception. For b=1b=1, W=(d+1)(d+2)/2W=(d+1)(d+2)/2, so repeating the prefixes costs Θ(d2)\Theta(d^2) against a single traversal’s Θ(d)\Theta(d). The exponential-tree argument cannot be used after its b>1b>1 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 O(d)O(d) active vertices and frames, plus an O(d)O(d) 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 O(bd)O(bd) 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

  1. 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.
  2. 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.
  3. 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.
  4. A run stops at max_depth=1 with 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?

Choose one answer

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

  1. AIMA Python — search algorithms (commit f104e03, 2026-06-30)
    AIMA Python contributors · 2026
  2. Depth-First Iterative-Deepening: An Optimal Admissible Tree Search
    Richard E. Korf · 1985
  3. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.