🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeIterative Deepening Search in Python

Finding a short route through a graph means deciding how far to search before trying longer routes. Iterative deepening depth-first search (IDDFS) repeats depth-limited searches with a larger edge limit until it finds a goal or reaches a chosen bound.
This article builds a Python search for an unweighted graph and compares its expansions with breadth-first search. It also shows how to prevent cycles by tracking the current path.
TL;DR
Iterative deepening depth-first search (IDDFS) runs depth-limited DFS again and again, increasing the limit until it finds a goal or reaches a bound you set.
- For an unweighted graph, the first goal it finds is at the shallowest reachable depth, when each iteration explores fully and neighbor order stays consistent.
- Track the current path to avoid cycles, and restart from the source for each limit.
- Use BFS when its frontier fits memory or when every edge has equal cost and you need fewer repeated visits.
- IDDFS does not minimize weighted path cost. Use a cost-aware algorithm for that task.
What Is Iterative Deepening Search?
IDDFS is the abbreviation for iterative deepening depth-first search.
A depth limit counts the edges along a route rather than the total number of nodes the search can inspect. At each level, the branching factor determines how many nodes are available to visit.
The image below sketches the search boundary around a root and its descendants, rather than a specific Python graph representation.

This is an uninformed search because it uses successor links and a goal test rather than a heuristic estimate of which node is promising.
I used a six-node adjacency list because its recorded expansion counts make the effect of neighbor order visible in the comparison.
The sample goal test compares one node with G. For several acceptable destinations, use a predicate that checks membership in a goal set. This keeps the goal rule separate from route traversal, so changing the accepted destinations does not require changing the traversal logic.
Finite branching means each fixed-depth pass has a finite number of routes to examine. When all edges cost the same, the first goal has minimum edge count, though neighbor order resolves ties. With a finite-depth goal, continuing the passes to its depth makes the search complete.
Set the maximum depth to cover the expected solution depth, because a goal beyond a user-chosen bound cannot be found by this search.
How to Find a Shortest Unweighted Path with IDDFS
The example passes the current route into a recursive search. It returns a route when it reaches the goal, or reports no route within that limit.
Step 1: Define a small adjacency-list graph
The sample has two equal-length routes from S to G. The search returns the first one found under adjacency-list order, so a different ordering can produce a different but equally shallow result.
For an undirected graph, each adjacency list stores outgoing moves in both directions for every connection.
Python dictionary keys must be hashable, so a structured state such as a board position needs an immutable key representation. A tuple of row values is one option for a grid. Keep the data used for equality aligned with the data used to generate neighbors, or a visually identical position may be treated as a different node.
GRAPH = {
"S": ["A", "B"],
"A": ["S", "C"],
"B": ["S", "D"],
"C": ["A", "G"],
"D": ["B", "G"],
"G": ["C", "D"],
}
Each listed node has an entry, including G, whose neighbors let the search continue if G is not the requested target.
Step 2: Stop a depth-limited pass at its boundary
Check for the goal before cutoff so start-equals-goal works at zero and a goal reached exactly at the bound is accepted.
def depth_limited_path(graph, start, goal, limit, path=None):
if path is None:
path = [start]
if start == goal:
return path.copy()
if limit == 0:
return None
for neighbor in graph.get(start, []):
if neighbor in path:
continue
result = depth_limited_path(
graph, neighbor, goal, limit - 1, path + [neighbor]
)
if result is not None:
return result
return None
The active-path check prevents cycles, while a global visited flag that ignores depth can hide a solution when another route reaches the same state with more depth remaining.
Step 3: Increase the limit and restart
Testing each bound in order returns the first available route, while reusing the same graph keeps every pass grounded in the same transitions.
def iterative_deepening(graph, start, goal, max_depth):
for limit in range(max_depth + 1):
path = depth_limited_path(graph, start, goal, limit)
if path is not None:
return path, limit
return None, None
The same graph data on every pass keeps the transition rules fixed while the bound changes.
Require max_depth to be a nonnegative integer. Clarify whether it counts edges or nodes before accepting user input.
Without a bound, depth-first search can remain on an infinite branch that contains no goal instead of returning to other branches.
Step 4: Run the search and compare its work with BFS
Save the complete runnable example below as dfid_search_demo.py and run python3 dfid_search_demo.py. The helper functions count each examined node, and the BFS comparison uses collections.deque to process queued paths in first-in, first-out order.
from collections import deque
GRAPH = {
"S": ["A", "B"],
"A": ["S", "C"],
"B": ["S", "D"],
"C": ["A", "G"],
"D": ["B", "G"],
"G": ["C", "D"],
}
def depth_limited_path(graph, start, goal, limit, path=None, expanded=None):
if path is None:
path = [start]
if expanded is not None:
expanded[0] += 1
if start == goal:
return path.copy()
if limit == 0:
return None
for neighbor in graph.get(start, []):
if neighbor in path:
continue
result = depth_limited_path(
graph, neighbor, goal, limit - 1, path + [neighbor], expanded
)
if result is not None:
return result
return None
def iterative_deepening(graph, start, goal, max_depth):
total_expanded = [0]
for limit in range(max_depth + 1):
path = depth_limited_path(graph, start, goal, limit, expanded=total_expanded)
if path is not None:
return path, limit, total_expanded[0]
return None, None, total_expanded[0]
def breadth_first_path(graph, start, goal):
queue = deque([(start, [start])])
expanded = 0
while queue:
node, path = queue.popleft()
expanded += 1
if node == goal:
return path, expanded
for neighbor in graph.get(node, []):
if neighbor not in path:
queue.append((neighbor, path + [neighbor]))
return None, expanded
def main():
path, depth, ids_expanded = iterative_deepening(GRAPH, "S", "G", 4)
bfs_path, bfs_expanded = breadth_first_path(GRAPH, "S", "G")
print(f"IDDFS path: {' -> '.join(path)}")
print(f"Depth limit: {depth}")
print(f"IDDFS expansions across limits: {ids_expanded}")
print(f"BFS path: {' -> '.join(bfs_path)}")
print(f"BFS expansions: {bfs_expanded}")
missing, _, _ = iterative_deepening(GRAPH, "S", "G", 1)
print(f"Goal within depth 1: {missing}")
if __name__ == "__main__":
main()
IDDFS path: S -> A -> C -> G
Depth limit: 3
IDDFS expansions across limits: 13
BFS path: S -> A -> C -> G
BFS expansions: 6
Goal within depth 1: None

I ran python3 dfid_search_demo.py and got the output shown above. IDDFS examined 13 nodes across its passes and BFS examined 6 on this graph, so treat these counts as an example rather than a general benchmark.
Each counter increments when IDDFS enters a recursive call or BFS removes an item from its queue, including the start and goal.
The bounded search also returned None at limit one, meaning it found no route within one edge. BFS processes nodes in queue order, so it can be preferable when its queue fits memory.
The BFS example uses deque.popleft to remove the oldest queued route. Python documents efficient appends and pops at either end of a deque, which avoids repeatedly shifting the remaining items as a front-removal from a list would.
Choose IDDFS when the goal depth is unknown and frontier storage is the tighter constraint. BFS can be preferable when its frontier fits memory and repeated visits are the larger concern.
Edge Cases and Complexity
Before applying the method to a larger graph, check how limits, cycles and edge costs interact. The table lists common symptoms and responses.
| Case | Symptom | Response |
|---|---|---|
| Cycle with no path guard | Recursive search follows repeated edges until Python raises RecursionError. | Skip neighbors already in the current path and keep a finite depth bound. |
| Goal beyond maximum depth | The bounded function returns None although a deeper route may exist. | Increase max_depth or use an unbounded strategy with a termination argument. |
| Weighted edges | The first shallow route can cost more than a longer route. | Use a cost-aware algorithm such as Dijkstra’s algorithm for nonnegative costs. |
| Many branches | Repeated shallow expansions take time. | Prefer BFS when its frontier fits available memory and shortest edge-count is the goal. |
| Very deep recursive route | Python’s recursion limit can be reached before the search limit. | Use an explicit stack or iterative implementation rather than increasing the interpreter limit blindly. |
Run the intentionally unguarded example with python3 dfid_cycle_failure.py to see how recursive search behaves on a cycle.
def naive_depth_limited_search(graph, node, goal, limit):
if node == goal:
return True
if limit == 0:
return False
for neighbor in graph.get(node, []):
if naive_depth_limited_search(graph, neighbor, goal, limit - 1):
return True
return False
if __name__ == "__main__":
cyclic_graph = {"A": ["B"], "B": ["A"]}
try:
print(naive_depth_limited_search(cyclic_graph, "A", "missing", 2000))
except RecursionError as error:
print(f"{type(error).__name__}: {error}")
RecursionError: maximum recursion depth exceeded

I ran the cyclic example and observed RecursionError: maximum recursion depth exceeded. Each recursive call followed the next edge without stopping a revisit to A or B.
For branching factor b, the largest number of outgoing choices at a node, and shallowest goal depth d in edges, textbook tree-search analysis gives IDDFS time on the order of b to the power d and auxiliary space on the order of b times d. BFS stores its frontier, which can grow exponentially with solution depth. The graph’s adjacency data is separate from this auxiliary search state.
An empty adjacency list is a dead end, while graph.get treats a missing key as having no neighbors. Validate node names at the input boundary when a typo should be an error rather than an ordinary no-route result.
Repeated neighbors in a list are legal input but make the search inspect the same transition more than once. Deduplicate the list when duplicates have no meaning.
The membership check in this implementation scans the path list, so each candidate edge may require work proportional to the current depth. A companion set can make membership checks faster, but it must be updated as recursion enters and leaves each node. The path list remains useful for reconstructing the answer.
The expression path + [neighbor] creates a new list at each recursive step. For long routes, append-and-pop backtracking avoids copying every prefix, but it must remove the node on every return path, including successful returns.
In an undirected graph, the source and goal may lie in separate connected components, so the search cannot reach that target from this start.
To stop as soon as a finite graph is exhausted, use separate results for a found path, a cutoff where a legal next step exceeded the limit, and a failure with no remaining route.
To use the example with string labels, preserve the dictionary shape and pass the selected start and goal to iterative_deepening. For numeric identifiers, the search function needs no changes because dictionary keys and list members can be any hashable values. If neighbors come from a database or generator, materialize them before starting the search.
For a deep search, an explicit stack avoids one Python call per edge. Its entries must preserve the depth boundary and enough route state for backtracking.
For graphs where duplicate states are common, define when two states are equivalent before adding a cache. A state reached with more remaining depth may still have options that an earlier shallow arrival could not explore, so a plain global visited set can prune a useful route. Cache the best known depth or remaining budget and verify that the pruning rule preserves paths that can still reach a goal.
Game-tree search uses iterative deepening for a different task: deepening a minimax evaluation before a time budget expires. That search repeatedly improves a move choice, while this implementation returns a route through graph edges.
IDA* is another related name, but its bound applies to accumulated path cost plus a heuristic estimate. This implementation counts edges and has no heuristic, so its depth limit cannot stand in for an IDA* cost threshold.
For a weighted map, a route with fewer edges can still have a larger total cost if one edge is expensive. Dijkstra’s algorithm handles nonnegative edge weights by selecting paths according to accumulated cost rather than edge depth.
The returned path contains both endpoints, so subtract one from its node count to get its edge count. If start equals goal, it contains one node and zero edges.
Conclusion
State the depth bound and route representation explicitly when adapting the example. Test a cycle, an absent goal and a start that already equals the goal before using a larger graph.
For the individual methods, see AskPython’s depth-first search in Python and breadth-first search in a graph. The Python deque documentation describes the queue used for the BFS comparison.
FAQ
These answers distinguish the search’s route-length guarantee from its memory and path-cost trade-offs.
Is iterative deepening search complete?
Yes, when the branching factor is finite, each bounded pass finishes, and a goal exists at a finite depth. A finite max_depth only guarantees a result within that bound.
Is IDDFS optimal for weighted graphs?
No. IDDFS finds a shallowest path by edge count when each pass is complete. A shorter route can have higher total weight, so use a cost-aware algorithm for weighted paths.
Why does IDDFS repeat nodes?
Each pass restarts at the source with a larger depth limit. Nodes near the source can therefore be expanded again, trading extra work for a smaller search frontier.
How do I stop cycles in Python IDDFS?
Track the nodes on the current route and skip a neighbor already on that route. Reset route state for each independent branch; global visited-state pruning needs depth-aware reasoning.


