Sub topic 15
Choosing Between BFS and DFS
This chapter assumes you have read the earlier chapters. You should know how to write BFS with a deque and a visited set, why BFS layers give unweighted shortest paths, and why BFS runs in O(V + E) time. It also assumes you have seen depth-first search (DFS) at least briefly. DFS is the traversal that follows one branch as deep as it can before backing up, usually written with recursion or an explicit stack.
On reachability problems the two algorithms do the same work. Both visit every reachable vertex once and inspect every edge once, so both cost O(V + E). The choice between them depends on three things: the order in which vertices are visited, the shape of the memory each one holds, and which structural facts each one exposes along the way.
One Loop, Two Frontiers
Both traversals keep a frontier of discovered vertices that have not yet been expanded. The only mechanical difference is which end of the frontier they take from.
That small change alters what the traversal guarantees. The program below runs both on the same graphs. It prints the visit order and the path each one finds to a goal.
from collections import deque
def bfs_order(graph, start):
visited = {start}
order = []
queue = deque([start])
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return order
def dfs_order(graph, start):
visited = set()
order = []
def visit(node):
visited.add(node)
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visit(neighbor)
visit(start)
return order
def bfs_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 dfs_path(graph, start, goal):
visited = set()
stack = [(start, [start])]
while stack:
node, path = stack.pop()
if node == goal:
return path
if node in visited:
continue
visited.add(node)
for neighbor in reversed(graph[node]):
if neighbor not in visited:
stack.append((neighbor, path + [neighbor]))
return None
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(bfs_order(graph, 'A')) # ['A', 'B', 'C', 'D', 'E', 'F']
print(dfs_order(graph, 'A')) # ['A', 'B', 'D', 'F', 'C', 'E']
detour = {'A': ['B', 'C'], 'B': ['C'], 'C': ['D'], 'D': []}
print(bfs_path(detour, 'A', 'D')) # ['A', 'C', 'D']
print(dfs_path(detour, 'A', 'D')) # ['A', 'B', 'C', 'D']DFS reaches D through the detour A → B → C → D because it commits to B first and never reconsiders. The path DFS finds is a real path, but nothing makes it short. BFS returns the two-edge path because it finishes every vertex at distance 1 before it looks at distance 2.
What Each Traversal Guarantees
BFS guarantees distance order. Vertices leave the queue in nondecreasing edge distance from the source. That is why the first time BFS reaches a vertex, it has found a fewest-edges path to it. It is also why BFS can stop early at the nearest goal.
DFS guarantees ancestry structure. When recursive DFS finishes a vertex, it has already finished every vertex reachable from it that was not already on the call stack. Several algorithms rely on that property:
- Cycle detection in directed graphs. An edge to a vertex that is still on the recursion stack (a "back edge") means there is a cycle.
- Topological sort. Reverse finishing order puts every vertex before its successors in a directed acyclic graph.
- Strongly connected components, bridges, and articulation points. Tarjan's and Kosaraju's algorithms use discovery and finish times, and BFS has nothing equivalent to them.
- Backtracking. Puzzles, permutations, and constraint search extend one partial solution at a time and undo the last choice when stuck, which is DFS by nature.
Plain reachability, connected components, flood fill, and bipartiteness testing work with either traversal. On those problems, choose based on memory and the risk of deep recursion.
Memory: Wide Frontiers Versus Deep Ones
Both algorithms use O(V) space in the worst case for the visited set. The frontiers behave very differently, though. The BFS queue can hold an entire layer at once. The DFS stack holds roughly one root-to-current path plus the unexplored siblings along it. The program below measures the peak frontier size of each on a complete binary tree.
from collections import deque
def binary_tree(depth):
n = 2 ** (depth + 1) - 1
return {i: [c for c in (2 * i + 1, 2 * i + 2) if c < n] for i in range(n)}
def bfs_peak(graph, start):
visited = {start}
queue = deque([start])
peak = 1
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
peak = max(peak, len(queue))
return peak
def dfs_peak(graph, start):
visited = set()
stack = [start]
peak = 1
while stack:
node = stack.pop()
if node in visited:
continue
visited.add(node)
for neighbor in reversed(graph[node]):
if neighbor not in visited:
stack.append(neighbor)
peak = max(peak, len(stack))
return peak
tree = binary_tree(10)
print(len(tree)) # 2047
print(bfs_peak(tree, 0)) # 1024
print(dfs_peak(tree, 0)) # 11On a tree with branching factor b and depth d, the BFS frontier grows like b^d, while the DFS frontier grows like b·d. For a finite graph that already fits in memory, this rarely matters, because the visited set costs O(V) either way. It matters a great deal for implicit graphs, such as puzzle states, game trees, or word ladders. In those graphs neighbors are generated on demand and the full vertex set would never fit in memory.
The trade-off reverses on long, thin graphs. On a path with 100,000 vertices, the BFS queue never holds more than one vertex. Recursive DFS, however, needs 100,000 stack frames.
Iterative Deepening: DFS Memory with BFS Answers
Sometimes you need the fewest-moves answer, the graph is implicit and huge, and the BFS frontier will not fit in memory. Iterative deepening DFS (IDDFS) handles this case. It runs a depth-limited DFS with limit 0, then 1, then 2, and so on, stopping at the first limit that reaches the goal. The first success happens at the shallowest goal depth, so the answer matches the one BFS would give, while memory stays at O(b·d).
The cost is repeated work. Shallow levels are re-explored on every round. When b ≥ 2, the deepest level dominates the total, so the overhead is a constant factor of about b/(b − 1). On general graphs with many cycles, a depth-limited search without a global visited set can revisit states many times, so IDDFS works best when the search space is close to a tree.
A Decision Guide
| Question you are answering | Prefer | Reason |
|---|---|---|
| Fewest edges from s to t, or distance to every vertex | BFS | Distance order is guaranteed |
| Nearest vertex with some property | BFS | It can stop at the first match |
| Distance from the nearest of many sources | Multi-source BFS | Seed the queue with every source |
| Edge weights are only 0 or 1 | 0-1 BFS | Uses a deque and needs no heap |
| General nonnegative weights | Dijkstra | Neither BFS nor DFS is correct |
| Directed cycle detection, topological order | DFS | Needs back edges or finish times |
| SCCs, bridges, articulation points | DFS | Needs discovery and low-link times |
| Enumerate all solutions, or backtrack | DFS | Extends and undoes one partial choice at a time |
| Reachability, components, flood fill, bipartite | Either | Same O(V + E) cost |
| Shortest moves in a huge implicit tree | IDDFS or bidirectional BFS | The BFS frontier is too wide |
Common Mistakes
- Swapping
popleft()forpop()and calling it DFS. If you keep the mark-on-enqueue rule from BFS and change only the pop end, you get a valid reachability search, but its visit order is not a true DFS order. Discovery and finish times from that version are wrong for topological sort and for cycle detection. A real iterative DFS either marks a vertex when it is popped, asdfs_pathdoes above, or keeps an explicit iterator for each stack frame. - Using DFS for shortest paths and then patching it. Updating distances during DFS ("relaxing" them) turns the search into an exponential-time search on some graphs. Use BFS.
- Using BFS on weighted graphs. BFS counts edges, not total weight. With weights larger than 1 it returns wrong answers. Use 0-1 BFS or Dijkstra instead.
- Choosing by habit on huge implicit graphs. Estimate the branching factor and depth first. A frontier of b^d states can exhaust memory long before the time limit is reached.
Exercise
You must find the minimum number of moves to solve a sliding puzzle whose state space has about 10^13 states and a branching factor of about 3. The best solution is at most 30 moves deep. Plain BFS runs out of memory. Name two alternatives that still guarantee the minimum, and state the main cost of each.
Show answer
Iterative deepening DFS keeps only the current path, about 30 states plus siblings, and still returns the minimum depth. Its cost is re-exploring shallow levels on each round, a constant factor of about b/(b − 1) = 1.5. It can also repeat states, because it keeps no global visited set. Bidirectional BFS searches from the start and the goal until the two frontiers meet. This cuts the frontier from about 3^30 to about 2·3^15 states. Its cost is that you must be able to generate predecessor states from the goal, and it still needs memory for both frontiers and their visited sets.
Exercise
For each task, choose BFS, DFS, or either, and give the reason: (1) order course prerequisites so each course comes after the courses it requires; (2) find the closest exit from a cell in a maze; (3) count the islands in a grid; (4) detect whether a directed dependency graph has a cycle.
Show answer
(1) DFS. Reverse postorder gives a topological order. Kahn's algorithm, a queue-based method that uses in-degrees, also works, but plain BFS from one source does not. (2) BFS, because distance order means the first exit dequeued is the closest. (3) Either, because each flood fill only needs reachability. BFS or iterative DFS avoids recursion-depth problems on large grids. (4) DFS. A back edge to a vertex still on the recursion stack signals a cycle. Kahn's algorithm can also detect a cycle when some vertices are never removed.
Exercise
A teammate turns the BFS function into "DFS" by replacing queue.popleft() with queue.pop() and keeping the mark-when-enqueued rule. They then use the visit order for topological sorting. Why can this fail?
Show answer
Marking at push time stops a vertex from being pushed again later, when a deeper branch reaches it. As a result, the vertex is expanded based on whichever parent pushed it first, not in true depth-first order. Finish times, or the reverse postorder taken from them, no longer guarantee that every vertex comes before all of its successors. Topological sort needs a true DFS: either recursion, or an iterative version that marks vertices when they are popped and records each vertex's finish only after all of its descendants are done.