Depth-Limited Search: Bounded Depth-First Search

Learn depth-limited search (DLS) for handling infinite state spaces with a depth bound, and how it relates to iterative deepening.

published: reading time: 19 min read author: Geek Workbench updated: November 12, 2026
Quick Summary

Depth-limited search bounds path depth and distinguishes a cutoff branch from a search that has no remaining reachable states. It finishes only when the branching is finite and the limit is finite. Iterative deepening is complete for finite branching when a solution exists at finite depth, and finds a least-edge solution when all step costs are equal.

Depth-Limited Search: Bounded Depth-First Search

Depth-Limited Search (DLS) modifies depth-first search by setting a maximum path depth. With finite branching, this prevents an infinite path from consuming the whole search; path tracking also avoids revisiting ancestors in a cycle.

With a finite depth limit and finite branching, DLS examines only finitely many nodes. A depth bound alone does not guarantee termination when a node has infinitely many successors. Solutions deeper than the limit are not found, so the result must distinguish a pruned branch from a fully explored failure.

Introduction

Depth-Limited Search (DLS) caps the path depth explored by DFS. On a finitely branching graph, a finite limit bounds the work, including when the graph contains cycles. With infinite branching, a node may still have infinitely many children to inspect. Solutions deeper than the limit are missed, so DLS returns a CUTOFF marker when it pruned a branch and failure when it exhausted the reachable branches without pruning.

When a depth-limited run cuts off a branch, Iterative Deepening Depth-First Search (IDDFS) can try a larger limit. With finite branching, IDDFS is complete if a solution exists at finite depth. It finds a least-edge solution only when every edge has the same cost; with different edge costs, use an algorithm that accounts for cost.

Use DLS when the depth bound is part of the problem or resource budget. Use IDDFS when branching is finite, solution depth is unknown, and all steps have equal cost. For a related two-frontier method, see Depth-Limited and Bidirectional Search; for graph representation choices, see Adjacency Lists and Matrices.

The Algorithm

This recursive example uses a fresh path per branch to avoid cycling back through an ancestor. It assumes each node has finitely many successors and limit is a non-negative integer.

CUTOFF = object()

def depth_limited_search(graph, start, goal, limit):
    def visit(node, remaining, path):
        if node == goal:
            return path

        children = [child for child in graph.get(node, ()) if child not in path]
        if remaining == 0:
            return CUTOFF if children else None

        saw_cutoff = False
        for child in children:
            result = visit(child, remaining - 1, path + [child])
            if result is CUTOFF:
                saw_cutoff = True
            elif result is not None:
                return result
        return CUTOFF if saw_cutoff else None

    return visit(start, limit, [start])

A node at the limit returns CUTOFF only if it has an unexplored child. If every reachable branch ends before the limit, the result is None (failure). This distinction lets iterative deepening know whether increasing the limit could help.

Iterative Deepening

The caller supplies a maximum bound so an unreachable goal in an infinite graph cannot make the example run forever. For finite branching, IDDFS finds a goal at finite depth if one exists. With equal edge costs it finds a shallowest solution; unequal costs need a cost-aware algorithm.

def iterative_deepening(graph, start, goal, max_depth):
    for limit in range(max_depth + 1):
        result = depth_limited_search(graph, start, goal, limit)
        if result is CUTOFF:
            continue
        if result is not None:
            return result
        return None  # All reachable branches were exhausted.
    return CUTOFF  # The bound was reached; a deeper solution may exist.

Self-check: cutoff versus failure

search_graph = {
    "start": ["branch", "leaf"],
    "branch": ["goal"],
    "leaf": [],
    "goal": [],
}

assert depth_limited_search(search_graph, "start", "goal", 0) is CUTOFF
assert depth_limited_search(search_graph, "start", "goal", 2) == ["start", "branch", "goal"]
assert depth_limited_search({"start": []}, "start", "missing", 2) is None

The first assertion says a deeper path may exist. The third says the finite search was exhausted without finding the goal.

When to Use DLS

Use DLS when:

  • You have a meaningful maximum path depth or resource budget
  • You need to report whether the bound pruned any branch
  • You are implementing IDDFS on a finitely branching graph

Don’t use DLS when:

  • Goal depth is unknown and might exceed your bound
  • You need a least-edge path with equal edge costs (use BFS or IDDFS)
  • The graph is small enough for BFS

DLS vs Other Search Algorithms

Aspect BFS DFS DLS IDDFS
Time O(b^d) O(b^m) O(b^L) O(b^d)
Space O(b^d) O(bm) O(bL) O(bd)
Complete Finite branching No No Finite branching and finite-depth solution
Optimal Equal edge costs No No Equal edge costs
Memory High Low Low Low

*b = branching factor, d = solution depth, m = max depth, L = depth limit

Trade-off Analysis

When choosing DLS over other search algorithms, consider these key trade-offs:

Trade-off DLS DFS BFS IDDFS
Completeness ❌ Not complete if depth unknown ❌ Can get stuck in infinite paths ✅ For finite branching ✅ For finite branching, if a finite-depth solution exists
Optimality ❌ Not optimal ❌ Not optimal ✅ Unit edge costs ✅ Unit edge costs
Space Efficiency ✅ O(bL) ✅ O(bm) ❌ O(b^d) ✅ O(bd)
Depth Guarantee ✅ Bounded exploration ❌ No bound ✅ Finds all depths ✅ Incremental depth
Termination ✅ Finite branching and finite bound ❌ May not terminate ✅ Finite branching ✅ Each bounded run finishes for finite branching
Implementation Complexity ✅ Simple ✅ Simple ❌ Needs queue ⚠️ Moderate

* L = depth limit, b = branching factor, d = solution depth, m = max graph depth

With finite branching, a finite depth bound limits a DLS run. IDDFS can then increase that bound until it finds a solution or reaches its configured maximum. Completeness requires a finite-depth solution; optimality requires equal step costs.

Cutoff Handling

The key challenge in DLS is distinguishing failures:

# Python doesn't have null markers in functions elegantly
# So we return a sentinel object

CUTOFF = object()  # Singleton sentinel

def search_with_proper_cutoff(graph, start, goal, limit):
    result = dls_with_sentinel(graph, start, goal, limit)

    if result is CUTOFF:
        print("Goal not found within depth limit")
        return None
    elif result is None:
        print("Goal not found (graph exhausted)")
        return None
    else:
        return result

Applications

  1. Game tree searching: Fixed-depth search can be extended with techniques such as quiescence search
  2. Pathfinding with depth bounds: When you only need paths up to certain length
  3. Planning with horizon: In AI planning, often search within planning horizon
  4. Network exploration: Crawling with depth limits

Production Failure Scenarios

  1. Setting limit too shallow: Solutions deeper than limit are missed entirely
  2. Setting limit too deep: Wastes computation exploring unnecessary depths
  3. Cycle handling: Must track visited nodes within the search to avoid infinite loops
  4. Path reconstruction: Must track parent pointers or maintain full path

Quick Recap Checklist

  • DLS bounds path depth; finite branching is still needed for a bounded run to finish
  • Returns CUTOFF when it prunes a branch at the limit, and failure when the bounded search is exhausted
  • Solutions deeper than limit are missed
  • IDDFS applies DLS repeatedly with increasing limits
  • IDDFS is complete for finite branching when a solution exists at finite depth
  • IDDFS finds a shallowest solution when edge costs are equal

Interview Questions

1. What is the cutoff marker in depth-limited search?

The cutoff marker means at least one branch was stopped at the depth limit and could continue if the bound increased. Failure means this bounded search exhausted its reachable branches without pruning one. A finite search cannot prove global unreachability in every infinite graph.

2. Why is Iterative Deepening preferred over pure DFS or BFS?

IDDFS uses depth-first memory while trying limits in increasing order. With finite branching and a solution at finite depth, it is complete. The first solution is shallowest when every edge has the same cost. A configured maximum limit means the algorithm may stop with CUTOFF before finding a deeper solution.

3. What is the time complexity of Iterative Deepening?

For a branching factor b and solution depth d, IDDFS explores approximately O(b^d) nodes—the same as BFS. At depth i, we explore b^i nodes, and summing b^0 + b^1 + ... + b^d = (b^(d+1) - 1) / (b - 1) ≈ b^d for large b. So we pay a small constant factor overhead compared to BFS, but get DFS's space efficiency. This makes IDDFS asymptotically optimal in both time and space for unweighted shortest path problems.

4. When would you choose DLS over IDDFS?

Choose plain DLS when you have a specific depth bound in mind and want to search within that exact limit. IDDFS is for when you don't know the depth and want to find the shallowest solution. If you know the goal is at depth ≤ 5 and you just want to know if it exists, DLS(5) is simpler. If you need the shallowest solution without knowing its depth, IDDFS is better. Also, DLS is useful for bounded rational decision-making where deeper solutions are deemed too costly regardless of quality.

5. How does DLS handle graphs with cycles?

DLS handles cycles by maintaining a visited path — tracking all nodes on the current search path. In the recursive implementation, the path list is checked before recursing into a neighbor. If the neighbor is already in the path, the branch is skipped (if neighbor not in path). This prevents infinite loops without needing a global visited set, which would be incorrect across different search branches. Without this check, DLS could loop infinitely even with a depth limit in graphs containing cycles shorter than the limit.

  • Path-tracking prevents re-visiting ancestors
  • No global visited set needed (unlike BFS)
  • Different branches can revisit nodes via different paths
6. What is the space complexity of DLS and how does it compare to BFS?

DLS has a space complexity of O(bL) where b is the branching factor and L is the depth limit. In the recursive implementation, the space is O(bL) because the call stack holds at most L frames, each iterating over up to b neighbors. In the iterative implementation using an explicit stack, it also uses O(bL) space.

  • DLS: O(bL) — significantly less than BFS's O(b^d)
  • BFS: O(b^d) — must store all nodes at the frontier level
  • DFS: O(bm) — similar to DLS but m (max depth) may be larger
  • This space advantage is the primary reason DLS/IDDFS is chosen over BFS for large graphs
7. Can DLS be implemented iteratively? Compare recursive vs iterative approaches.

Yes, DLS can be implemented both recursively and iteratively. The recursive approach is cleaner and naturally tracks the depth limit by passing limit - 1 in each call, but risks stack overflow for deep limits. The iterative approach uses an explicit stack of (node, depth, path) tuples, avoiding recursion limits and giving more control over the search order.

  • Recursive: simpler code, natural depth tracking, risk of stack overflow
  • Iterative: more complex, explicit stack, no recursion depth issues
  • Both produce the same results; choose based on depth limit size and language constraints
8. What happens if the depth limit is set too shallow or too deep?

A too-shallow limit causes DLS to miss solutions entirely — it returns CUTOFF even though the goal exists at a deeper level. This is the classic false-negative problem. A too-deep limit wastes computation exploring unnecessary depths, degrading performance without bound, though DLS still terminates.

  • Too shallow: missed solutions, false negatives (returns CUTOFF)
  • Too deep: wasted computation, approaches DFS behavior
  • IDDFS solves this by trying all limits incrementally
  • Choosing the right L requires domain knowledge or adaptive approaches
9. How does DLS relate to quiescence search in game AI?

Quiescence search extends DLS beyond the normal depth limit when the current game position is "noisy" — e.g., undecided captures in chess. Instead of a hard cutoff at depth L, quiescence search continues until the position becomes "quiet" (no tactical sequences). This applies DLS concepts adaptively: the depth limit isn't a strict number but context-dependent.

  • Standard DLS: hard depth cutoff, may miss tactical sequences
  • Quiescence search: variable-depth cutoff based on position stability
  • Core concept is the same — bounded search — but with an adaptive, content-aware bound
10. What are the real-world applications where DLS is the most appropriate choice?

DLS shines in scenarios with known depth bounds or resource constraints:

  • Web crawling: Respect robots.txt crawl-depth limits while avoiding infinite spider traps
  • Compiler AST analysis: Bounded recursion-depth checks to prevent stack overflows in static analysis
  • Game tree search: Alpha-beta pruning with a fixed ply depth, extended by quiescence search
  • Database query planning: Bounded join-enumeration depth in query optimizers
  • AI planning with horizons: Planning within a fixed horizon where deeper plans are too costly or change too frequently
11. Explain the difference between depth-limited search and depth-first search in terms of termination guarantees.

DFS can follow an infinite path or cycle indefinitely without cycle handling. DLS bounds path depth, but it finishes only if each expanded node has finitely many successors and the limit is finite. Infinite branching can prevent the algorithm from completing even at a shallow limit.

  • DFS: May not terminate in cyclic or infinite graphs
  • DLS: Finishes for a finite bound when branching is finite
  • DLS returns CUTOFF only when a branch was pruned at the bound; a fully explored search returns failure
12. How would you implement DLS to find ALL solutions within a depth bound, not just one?

To find all solutions within a depth bound, modify DLS to collect results instead of returning on first match. In the recursive implementation, when node == goal, add the path to a solutions list rather than returning. Continue exploring other branches even after finding a solution. For the iterative version, exhaust the stack before returning. This approach explores the entire bounded space and returns every valid path from start to goal within depth L.

  • Collect all paths reaching the goal before returning
  • Continue recursing on siblings after finding a solution
  • Use a solutions list passed by reference or as a global accumulator
  • Return the list (possibly empty for no solutions) instead of a single path
13. What is the role of the CUTOFF sentinel, and why can't we just return None for both cutoff and failure?

CUTOFF means at least one branch was pruned at the limit, so a deeper search may find a goal. Failure means the bounded search exhausted its reachable branches without pruning one. A general search over an infinite graph cannot prove global unreachability from a finite bound alone.

  • CUTOFF = at least one branch may continue beyond the current limit
  • None = this bounded run exhausted its reachable branches
  • IDDFS is complete for finite branching when a finite-depth solution exists
14. In Iterative Deepening, why is the overhead of re-exploring upper levels acceptable?

Under a uniform branching-factor approximation, IDDFS revisits nodes near the root while increasing the limit. Its total work is still O(b^d) for branching factor b and solution depth d, while the active search path uses O(bd) space. These bounds assume finite branching; optimality is for equal step costs.

  • Upper levels re-explored: (b^d - 1)/(b - 1) ≈ b^d / (b - 1)
  • Deepest level: b^d nodes
  • Total: ~b^d * (1 + 1/(b-1)) ≈ b^d for large b
15. Can DLS be combined with bidirectional search? What are the advantages?

A two-frontier search can reduce work when the graph is unweighted, the target is specific, and predecessors can be generated efficiently. The O(b^(d/2)) estimate assumes roughly balanced branching and meeting depths; it is not a node-count guarantee. For the conditions and implementation, see [Depth-Limited and Bidirectional Search](/blog/technical/depth-limited-bidirectional-search/).

  • Two bounded searches from opposite ends
  • Time: O(b^(d/2)) if meet point is balanced
  • Space: O(b^(d/2)) combined (each side)
  • Requires a goal node to search backward from
16. How does DLS handle weighted graphs vs unweighted graphs differently?

Basic DLS doesn't account for edge weights — it counts depth in edges, not cumulative cost. For weighted graphs, iterative deepening on cost bounds (IDA*) replaces depth with path cost: increment the cost limit until the goal is found. This is fundamentally different because a shorter path in edges might have higher cost than a longer path. DLS concepts transfer but the bound metric changes from hop-count to path-cost.

  • Unweighted: bound = number of edges from start
  • Weighted: bound = cumulative path cost g(n)
  • IDA* uses cost-bound instead of depth-bound
  • Heuristic h(n) guides which branches to explore first
17. What happens when DLS encounters a node at exactly the depth limit?

DLS checks whether the node is the goal before applying the limit. At the limit, it returns CUTOFF only if there is an unvisited child that would have been explored at a larger bound; a leaf returns failure. The goal depth is inclusive while expansion beyond the bound is excluded.

  • Goal at depth L is found (checked before limit test)
  • Children of nodes at depth L are not explored
  • Limit is inclusive for goals, exclusive for expansion
18. Describe a scenario where DLS would outperform BFS completely.

Consider a maze with a known exit depth where the solution path is exactly 50 edges long, but the graph is enormous (millions of nodes). BFS would need to explore all nodes at depths 0 through 50, storing millions of nodes at the frontier — requiring gigabytes of memory. DLS with limit=50 explores only along valid paths, using O(b*50) space regardless of total graph size. If you know the solution depth is bounded, DLS's memory efficiency is decisive.

  • Memory: BFS = O(b^50), DLS = O(b*50)
  • BFS gets stuck with exponential memory growth
  • DLS explores only along solution-bound paths
  • Works when depth bound is known and relatively small
19. How does path tracking in DLS affect performance, and can it be optimized?

Path tracking via the path list enables cycle detection but is O(L) for membership checks with list — each neighbor not in path scans the entire current path. For deep searches with high branching factors, this adds up. Optimization options: use a set for O(1) lookup while maintaining path for reconstruction, or use parent pointer arrays for O(1) path reconstruction without path list overhead. The performance impact is most noticeable for deep limits with large branching factors.

  • List membership: O(L) per check
  • Set for visited: O(1) but loses path order
  • Parent pointers: O(1) reconstruction without storing full path
  • Trade-off: complexity vs memory vs reconstruction needs
20. In a game AI context, how would you adapt DLS for a time-limited search that must return the best move found so far?

For time-limited game AI, use DLS with iterative deepening and track the best solution found so far. Start at depth 1 and increment depth as time permits. If time runs out mid-search, return the best completed solution. For alpha-beta pruning, combine with move ordering — explore the best-looking moves first at each depth so earlier cutoffs happen. The adaptive approach: every completed depth gives you a valid move, with deeper iterations potentially finding better solutions.

  • IDDFS provides natural anytime algorithm
  • Track best move found at each completed depth
  • Combine with move ordering for better pruning
  • Return best completed result when time expires
  • Quiescence search extends beyond fixed depth for tactical stability

Further Reading

To deepen your understanding of DLS and related search algorithms, explore these topics:

  1. Iterative Deepening A* (IDA*) — Combines IDDFS with heuristic guidance for informed search, using a cost-bound instead of depth-bound. Ideal for puzzles like the 15-puzzle where the state space is large but well-structured.
  2. Bidirectional Search — Searches forward from start and backward from goal simultaneously, often meeting in the middle for exponential speedup. Can be combined with depth-bounding for memory-efficient variants.
  3. Heuristic Search (A*) — For weighted graphs, A* uses f(n) = g(n) + h(n) to guide search efficiently toward the goal. DLS concepts appear in depth-bounded A* variants.
  4. Constraint Satisfaction Problems (CSPs) — Depth-bounded backtracking (a form of DLS) is fundamental to solving CSPs like Sudoku and N-Queens with bounded lookahead.
  5. Quiescence Search in Game AI — Extends DLS beyond the horizon when the current position is still in flux (e.g., undecided captures in chess), creating an adaptive, content-aware depth limit.
  6. Monte Carlo Tree Search (MCTS) — Modern game-playing algorithms that use selective depth-limited rollouts guided by an exploration-exploitation trade-off (UCT).

For practical implementations, compare DLS with Depth-Limited and Bidirectional Search and Search Scaling. DLS and depth bounds also appear in:

  • Web crawlers: Respecting crawl-depth limits from robots.txt while avoiding spider traps
  • Database query optimizers: Bounded join-enumeration depth for efficient query planning
  • Compiler static analysis: Recursion-depth limits in AST traversal and cycle detection
  • Network protocol verification: Bounded model checking with depth limits to verify finite-state systems

Conclusion

Depth-Limited Search explores paths up to a finite limit. With finite branching, it distinguishes a pruned branch (CUTOFF) from an exhausted bounded search (failure). IDDFS increases the limit and is complete when branching is finite and a solution exists at finite depth; it returns a shallowest solution only when step costs are equal. For the paired two-frontier approach, see Depth-Limited and Bidirectional Search and Search Scaling.

Category

Related Posts

Depth-Limited & Bidirectional Search

Explore search algorithm variants: depth-limited search for bounded recursion, and bidirectional search for O(b^d/2) complexity improvement.

#search-algorithms #depth-limited-search #bidirectional-search

Articulation Points & Bridges in Graphs

Learn how DFS low-link values identify articulation points and bridges in undirected graphs, including root cases and disconnected components.

#articulation-points #bridges #graph-algorithms

Bellman-Ford Algorithm: Shortest Paths with Negative Weights

Learn the Bellman-Ford algorithm for single-source shortest paths including negative edge weights and negative cycle detection.

#bellman-ford #shortest-path #graph-algorithms