BFS vs DFS: When to Use Each
BFS vs DFS: When to Use Each
Breadth-First Search (BFS) and Depth-First Search (DFS) are the two fundamental ways to explore a graph or tree. They both visit every reachable node exactly once, both run in O(V + E) time, but they explore in completely different orders — and that difference determines which problems each one solves well.
How BFS Works
BFS uses a queue (FIFO). It visits all neighbors of the current node before moving deeper. Think of it like ripples expanding outward from a stone dropped in water — layer by layer, level by level.
Because BFS explores nodes in order of their distance from the source, it guarantees the shortest path on unweighted graphs.
How DFS Works
DFS uses a stack (LIFO) — either explicitly or through recursion's call stack. It plunges as deep as possible along one branch before backtracking.
DFS does not guarantee shortest paths. It might find a path that takes 50 steps when a 3-step path exists.
Code Snippets
Graph Setup
class Graph:
def __init__(self, num_nodes: int):
self.num_nodes = num_nodes
self.adjacency_list = [[] for _ in range(num_nodes)]
def add_edge(self, from_node: int, to_node: int):
self.adjacency_list[from_node].append(to_node)
self.adjacency_list[to_node].append(from_node)
def get_neighbors(self, node: int) -> list[int]:
return self.adjacency_list[node]
Breadth-First Search
def breadth_first_search(graph: Graph, start_node: int) -> list[int]:
"""Explore graph level by level using a queue."""
visited = [False] * graph.num_nodes
visited[start_node] = True
queue = [start_node]
head = 0
visit_order = []
while head < len(queue):
current_node = queue[head]
head += 1
visit_order.append(current_node)
for neighbor in graph.get_neighbors(current_node):
if not visited[neighbor]:
visited[neighbor] = True
queue.append(neighbor)
return visit_order
Depth-First Search
def depth_first_search(graph: Graph, start_node: int) -> list[int]:
"""Explore graph branch by branch using a stack."""
visited = [False] * graph.num_nodes
stack = [start_node]
visit_order = []
while stack:
current_node = stack.pop()
if visited[current_node]:
continue
visited[current_node] = True
visit_order.append(current_node)
for neighbor in graph.get_neighbors(current_node):
if not visited[neighbor]:
stack.append(neighbor)
return visit_order
The Key Trade-Off: Memory
BFS must store the entire frontier — all nodes at the current depth level. For wide graphs, this memory cost is enormous.
DFS only stores the current path. For a tree with depth 20 and branching factor 10, DFS holds ~20 nodes in memory while BFS might hold millions.
When to Choose BFS
- Shortest path on unweighted graphs — BFS is optimal here
- Level-order traversal — processing nodes layer by layer
- Finding nodes within k steps — BFS naturally explores by distance
When to Choose DFS
- Detecting cycles — DFS back-edges reveal cycles naturally
- Topological sorting — DFS post-order gives reverse topological order
- Backtracking problems (Sudoku, N-Queens) — DFS is the natural recursive approach
- Memory-constrained scenarios — DFS uses O(depth) vs BFS O(branching^depth)
Summary Table
| Property | BFS | DFS |
|---|---|---|
| Data structure | Queue | Stack |
| Shortest path (unweighted) | Yes | No |
| Memory usage | O(branching^depth) | O(depth) |
| Best for | Shortest path, levels | Cycles, topological sort, backtracking |