Sub topic 17
Choosing Between DFS, BFS, and Iterative Deepening
This chapter assumes you can write recursive and iterative DFS, that you know DFS runs in O(V + E) time on an adjacency list, and that you have met breadth-first search (BFS) at least briefly. The aim is practical: given a problem, decide which traversal to use and know what goes wrong if you pick the wrong one.
All three strategies visit the same vertices. They differ in the order they visit them, and that order controls three properties: whether the first path found to a goal is the shortest one, how much memory the search needs, and which structural facts about the graph the search reveals.
How the Three Strategies Order Their Work
DFS keeps a stack, either the call stack or an explicit one, and always extends the newest path. BFS keeps a FIFO queue, a first-in-first-out list, and finishes every vertex at distance k before it touches any vertex at distance k + 1. Iterative deepening DFS (IDDFS) runs a depth-limited DFS with limit 0, then 1, then 2, and so on, until the goal turns up.
The example below runs all three on a graph where they disagree. Vertex A reaches E directly, and also through the long route B → C → D.
from collections import deque
def dfs_path(graph, start, goal, path=None):
if path is None:
path = [start]
if start == goal:
return path
for neighbor in graph[start]:
if neighbor not in path:
result = dfs_path(graph, neighbor, goal, path + [neighbor])
if result is not None:
return result
return None
def bfs_shortest_path(graph, start, goal):
parent = {start: None}
queue = deque([start])
while queue:
node = queue.popleft()
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1]
for neighbor in graph[node]:
if neighbor not in parent:
parent[neighbor] = node
queue.append(neighbor)
return None
def depth_limited(graph, node, goal, limit, path):
if node == goal:
return list(path)
if limit == 0:
return None
for neighbor in graph[node]:
if neighbor not in path: # avoid cycles along the current path
path.append(neighbor)
result = depth_limited(graph, neighbor, goal, limit - 1, path)
path.pop()
if result is not None:
return result
return None
def iddfs(graph, start, goal, max_depth):
for limit in range(max_depth + 1):
result = depth_limited(graph, start, goal, limit, [start])
if result is not None:
return result
return None
graph = {"A": ["B", "E"], "B": ["C"], "C": ["D"], "D": ["E"], "E": []}
print(dfs_path(graph, "A", "E")) # ['A', 'B', 'C', 'D', 'E']
print(bfs_shortest_path(graph, "A", "E")) # ['A', 'E']
print(iddfs(graph, "A", "E", 10)) # ['A', 'E']DFS commits to B because B is listed first, and it returns the first path it completes, which has four edges. BFS and IDDFS both return the one-edge path. BFS gets it because it explores in distance order. IDDFS gets it because a goal at depth d cannot be found until the limit reaches d, and every shallower limit has already failed.
Correctness: Who Finds the Shortest Path
In an unweighted graph, BFS gives shortest paths measured in edge count. When BFS first dequeues a vertex, no shorter route to it exists. IDDFS gives the same guarantee for the first goal it reaches. Plain DFS gives no such guarantee. The path it returns depends on the order of the adjacency lists, so reordering the input can change the answer.
None of the three handles weighted shortest paths. If edges have different costs, use Dijkstra's algorithm when weights are non-negative, or 0-1 BFS when every weight is 0 or 1.
Memory: The Frontier Versus the Path
Memory use is often the deciding factor. Take a search tree with branching factor b (children per node) and goal depth d.
- BFS stores the whole frontier. At depth d the frontier can hold about b^d vertices.
- DFS stores the current path plus, for each vertex on it, the position in its neighbor list. That costs O(d) frames, or O(b·d) if each frame holds its unexplored siblings.
- IDDFS is a DFS, so it has the same O(d) or O(b·d) memory.
For b = 10 and d = 8, a BFS frontier of about 100 million states may not fit in RAM. A DFS path eight frames deep costs almost nothing.
On an explicit graph with V vertices, both DFS and BFS need O(V) for the visited set anyway, so this gap matters less there. It matters most on implicit graphs, where vertices are generated on demand: puzzle states, game trees, configuration spaces. Those graphs are too large to store, and you cannot afford a visited set covering all of them.
The Cost of Repeating Work in IDDFS
IDDFS looks wasteful because it re-explores shallow levels on every iteration. On trees with branching factor b > 1, the waste is small, because the deepest level dominates the total. A node at depth i is generated once for each limit from i to d, which is (d + 1 − i) times.
| Depth i | Nodes at depth (b = 10) | Times generated by IDDFS (d = 5) | Total |
|---|---|---|---|
| 0 | 1 | 6 | 6 |
| 1 | 10 | 5 | 50 |
| 2 | 100 | 4 | 400 |
| 3 | 1,000 | 3 | 3,000 |
| 4 | 10,000 | 2 | 20,000 |
| 5 | 100,000 | 1 | 100,000 |
IDDFS generates 123,456 nodes. BFS generates 111,111. The overhead is about 11%, and in exchange memory drops from roughly 100,000 frontier entries to a handful of stack frames. With b = 2 the overhead is about 2×, which is still a constant factor.
Structure: What Only DFS Gives You
Some problems ask about the graph's structure rather than about distances. Topological sort, cycle detection with gray vertices, strongly connected components, and bridges and articulation points all depend on DFS properties. Those properties include the nesting of discovery and finish times, the distinction between back edges and cross edges, and low-link values propagated up a path. BFS visits vertices level by level and does not maintain a current path, so it has no back-edge concept to work with. (Kahn's algorithm sorts topologically with a queue, but it works from in-degree counts, which is a different mechanism.)
DFS also fits backtracking. A partial solution lives on the path: you extend it, test it, undo the last step, and try the next option. BFS would have to store every partial solution at once.
Practical Failure Modes
- Recursion depth. CPython's default recursion limit is 1000, and you can check it with
sys.getrecursionlimit(). A recursive DFS on a path-shaped graph or a 1000×1000 grid will raiseRecursionError. Raising the limit can crash the interpreter with a C stack overflow, so convert to an explicit stack instead. - Infinite or very deep branches. On an infinite implicit graph, plain DFS can follow one branch forever and never return. BFS and IDDFS are complete: if a goal exists at finite depth and the branching factor is finite, they will find it.
- Goal near the root but graph enormous. BFS or IDDFS stops early. DFS may wander deep into the wrong subtree first.
- Goals scattered deep and plentiful. DFS often finds some solution fastest, which suits "does any solution exist" questions.
Summary Table
| Property | DFS | BFS | IDDFS |
|---|---|---|---|
| Shortest path (unweighted) | No | Yes | Yes |
| Memory on tree search | O(b·d) | O(b^d) | O(b·d) |
| Complete on infinite graphs | No | Yes | Yes |
| Re-explores vertices | No (with visited set) | No | Yes, shallow levels |
| Exposes back edges, finish order | Yes | No | No |
| Natural for backtracking | Yes | No | Partly |
Exercise
You must find the minimum number of moves to solve a sliding-tile puzzle whose state space has about 10^13 states and an average branching factor near 3. Which strategy do you choose, and what risk must you manage?
Show answer
Choose iterative deepening DFS (in practice IDA*, its heuristic-guided version). BFS needs the fewest-moves guarantee but would have to hold a frontier far too large for memory, while plain DFS gives no shortest-path guarantee. The risk is re-exploring the same states through different move orders, so prune moves that immediately undo the previous move, or add a bounded transposition table.
Exercise
A teammate's recursive DFS for "shortest path in an unweighted maze" passes every sample test but fails hidden tests with wrong answers on some inputs and RecursionError on others. Explain both failures and give the fix.
Show answer
The wrong answers happen because DFS returns the first path it completes, and that path depends on neighbor order, so it is not guaranteed to be the shortest. The RecursionError happens because large mazes produce paths deeper than CPython's default limit of 1000 frames. Replacing the code with BFS over a deque, keeping a parent map, fixes both: BFS gives shortest paths and does not recurse.
Exercise
For branching factor b = 2 and goal depth d = 3, how many nodes do BFS and IDDFS each generate? Count the root.
Show answer
BFS generates 1 + 2 + 4 + 8 = 15. IDDFS generates each depth-i node (4 − i) times: 4·1 + 3·2 + 2·4 + 1·8 = 4 + 6 + 8 + 8 = 26. That is about 1.7 times as many, which shows the overhead is larger when the branching factor is small.