Sub topic 17
Choosing Between DFS, BFS, and Iterative Deepening
This chapter assumes you know recursive and iterative DFS, the O(V + E) analysis from earlier chapters, and how a queue differs from a stack. The question here is practical. You have a search problem, so which traversal should you use?
The Working Model
All three algorithms visit vertices in a different order:
- DFS follows one path as deep as it goes, then backtracks. Its frontier is a stack, either explicit or the call stack.
- BFS (breadth-first search) visits every vertex at distance 1, then distance 2, and so on. Its frontier is a queue.
- Iterative deepening DFS (IDDFS) runs a depth-limited DFS with limit 0, then 1, then 2, and so on until it finds the target. It visits vertices in roughly the same layer order as BFS while using only DFS-sized memory.
| Property | DFS | BFS | IDDFS |
|---|---|---|---|
| Time on explicit graph | O(V + E) | O(V + E) | O(b^d) on trees, plus repeated work |
| Memory | O(depth) | O(width of widest layer) | O(depth) |
| Shortest path (unweighted) | No | Yes | Yes |
| Works on infinite or huge implicit graphs | Risky, may never return | Yes, if memory lasts | Yes |
| Gives finish times, back edges, low-links | Yes | No | No |
In the table, b is the branching factor and d is the depth of the shallowest goal.
Seeing the Difference in Code
from collections import deque
def dfs_path(graph, node, target, visited=None):
if visited is None:
visited = set()
visited.add(node)
if node == target:
return [node]
for neighbor in graph[node]:
if neighbor not in visited:
rest = dfs_path(graph, neighbor, target, visited)
if rest:
return [node] + rest
return None
def bfs_path(graph, start, target):
parent = {start: None}
queue = deque([start])
while queue:
node = queue.popleft()
if node == target:
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, target, limit, path):
if node == target:
return path
if limit == 0:
return None
for neighbor in graph[node]:
if neighbor not in path:
found = depth_limited(graph, neighbor, target, limit - 1, path + [neighbor])
if found:
return found
return None
def iddfs(graph, start, target, max_depth):
for limit in range(max_depth + 1):
found = depth_limited(graph, start, target, limit, [start])
if found:
return found
return None
graph = {"A": ["B", "C"], "B": ["D"], "C": ["E"], "D": ["E"], "E": []}
print(dfs_path(graph, "A", "E")) # ['A', 'B', 'D', 'E']
print(bfs_path(graph, "A", "E")) # ['A', 'C', 'E']
print(iddfs(graph, "A", "E", 10)) # ['A', 'C', 'E']DFS returns a valid path, but the path is not the shortest one. BFS and IDDFS both find the two-edge path.
A Decision Guide
Common Errors
- Using DFS for shortest paths. DFS returns the first path it finds, and that path depends on the order of the adjacency lists.
- Assuming IDDFS is wasteful. On a tree with branching factor b, the last layer dominates the total work. The repeated shallow searches add only about a factor of b/(b−1).
- Running recursive DFS on deep graphs. Python's default recursion limit is about 1000. Long paths need the iterative version.
- Using BFS on weighted graphs. Neither BFS nor IDDFS handles edge weights. Use Dijkstra's algorithm instead.
Exercise
You are solving a puzzle whose states form an implicit graph with branching factor about 10. The shallowest solution is around depth 12, and you need the fewest moves. Which traversal should you use, and why?
Show answer
Use IDDFS. BFS would have to store a frontier of roughly 10^12 states. Plain DFS uses little memory but can follow a deep branch forever and gives no fewest-moves guarantee. IDDFS finds the shallowest solution with O(depth) memory, and the repeated work costs only about 10/9 of a single search.
Exercise
Why does dfs_path return ['A', 'B', 'D', 'E'] instead of the shorter ['A', 'C', 'E']?
Show answer
B comes before C in A's adjacency list. DFS commits to B, follows it to D and then to E, and returns as soon as it reaches the target. It never compares that path with alternatives.