Graph traversal is the backbone of many technical interviews. From routing Uber rides to recommending friends on social networks, graphs model complex relationships. In an interview setting, you will rarely be asked to simply "implement BFS." Instead, you will face problems disguised as 2D grids, social networks, or dependency trees where Breadth-First Search (BFS) or Depth-First Search (DFS) is the underlying engine. Mastering these two traversal patterns is non-negotiable for any software engineer preparing for interviews at top tech companies.
When to use this pattern
Before writing any code, you need to identify whether a problem requires a graph traversal and, more importantly, whether to use BFS or DFS. While both algorithms can visit all nodes in a connected component, their traversal order makes them suited for entirely different classes of problems.
Breadth-First Search (BFS)
BFS explores the graph level by level, radiating outward from the starting node. Think of it like dropping a stone in a pond and watching the ripples expand.
Signals to use BFS:
- Shortest path in an unweighted graph: "Find the minimum number of steps to reach the target."
- Level-order traversal: "Find all friends at exactly 3 degrees of separation."
- Multi-source propagation: "Given multiple infected computers, how long until the whole network is infected?"
Depth-First Search (DFS)
DFS dives as deep as possible along a single path before backtracking. Think of it like navigating a maze by keeping your hand on the right wall until you hit a dead end, then turning back.
Signals to use DFS:
- Exhaustive search / Backtracking: "Find all possible paths from start to finish."
- Cycle detection: "Can these courses be completed given their prerequisites?" (Topological sort).
- Connected components: "Count the number of islands in a grid." (BFS works here too, but DFS is often less code).
| Feature | BFS (Breadth-First Search) | DFS (Depth-First Search) |
|---|---|---|
| Data Structure | Queue (FIFO) | Stack (LIFO) or Recursion |
| Traversal Order | Level by level (wide) | Deep into one path first |
| Shortest Path | Yes (for unweighted graphs) | No (finds a path, not the shortest) |
| Memory (Space) | O(W) where W is max width | O(H) where H is max depth |
| Best used for | Shortest path, closest nodes | Cycle detection, backtracking |
The core idea
To traverse a graph safely without getting stuck in infinite loops, we must keep track of the nodes we have already visited. This is typically done using a visited set or boolean array.
Let's visualize a simple graph and see how both algorithms traverse it.
BFS Traversal Order: A -> B -> C -> D -> E -> F
BFS visits the starting node A, then all its immediate neighbors (B, C), then the neighbors of B (D, E), and finally the neighbors of C (F).
DFS Traversal Order: A -> B -> D -> E -> C -> F
DFS visits A, dives into B, dives into D (dead end), backtracks to B, dives into E (dead end), backtracks all the way to A, dives into C, and finally dives into F.
Template
Memorizing these core templates will give you a solid foundation. Notice how BFS relies on a Queue, while DFS relies on the Call Stack (recursion).
BFS Template
from collections import deque
def bfs(graph, start):
visited = set([start])
queue = deque([start])
while queue:
node = queue.popleft()
# Process the current node here
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)DFS Template (Recursive)
def dfs(graph, node, visited=None):
if visited is None:
visited = set()
visited.add(node)
# Process the current node here
for neighbor in graph[node]:
if neighbor not in visited:
dfs(graph, neighbor, visited)Worked examples
Let's apply these templates to three classic interview problems. We will cover a grid DFS, a multi-source grid BFS, and a cycle detection DFS.
Example 1: Number of Islands (Grid DFS)
Problem: Given an m x n 2D binary grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
Approach:
We can iterate through every cell in the grid. Whenever we encounter a '1', we have found a new island. We increment our island count and launch a DFS to "sink" the island (turn all connected '1's into '0's). This prevents us from double-counting the same island later.
def numIslands(grid):
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
islands = 0
def dfs(r, c):
# Base case: out of bounds or water
if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == '0':
return
grid[r][c] = '0' # Mark as visited by sinking the land
# Explore all 4 directions
dfs(r + 1, c)
dfs(r - 1, c)
dfs(r, c + 1)
dfs(r, c - 1)
for r in range(rows):
for c in range(cols):
if grid[r][c] == '1':
islands += 1
dfs(r, c)
return islandsComplexity:
- Time:
O(M \times N)whereMis rows andNis columns. We visit every cell a constant number of times. - Space:
O(M \times N)in the worst case (if the entire grid is one giant island, the recursion stack will goM \times Ndeep).
Example 2: Rotting Oranges (Multi-source BFS)
Problem: You are given an m x n grid where 0 represents an empty cell, 1 represents a fresh orange, and 2 represents a rotten orange. Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
Approach: Because the rotting process happens simultaneously from all initially rotten oranges, this is a "shortest path" problem from multiple starting points. We use a multi-source BFS.
- Enqueue all initially rotten oranges and count the total number of fresh oranges.
- Process the queue level by level (minute by minute).
- For each rotten orange, infect its fresh neighbors, decrement the fresh count, and enqueue the newly rotten neighbors.
- If the fresh count reaches 0, return the minutes. If the queue empties and fresh oranges remain, return
-1.
from collections import deque
def orangesRotting(grid):
rows, cols = len(grid), len(grid[0])
queue = deque()
fresh_count = 0
# Step 1: Initialize queue with all rotten oranges
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append((r, c))
elif grid[r][c] == 1:
fresh_count += 1
if fresh_count == 0:
return 0
minutes = 0
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
# Step 2: BFS level by level
while queue and fresh_count > 0:
minutes += 1
# Process all oranges rotten at the current minute
for _ in range(len(queue)):
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
# If neighbor is fresh, rot it
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = 2
fresh_count -= 1
queue.append((nr, nc))
return minutes if fresh_count == 0 else -1Complexity:
- Time:
O(M \times N)to scan the grid initially, andO(M \times N)for the BFS. - Space:
O(M \times N)for the queue in the worst case.
Example 3: Course Schedule (Cycle Detection)
Problem: There are numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [a, b] indicates that you must take course b first if you want to take course a. Return true if you can finish all courses. Otherwise, return false.
Approach: This is a classic cycle detection problem in a Directed Graph. If there is a cycle (e.g., A requires B, and B requires A), it's impossible to finish. We can solve this using a 3-color DFS:
0(Unvisited): Node hasn't been processed.1(Visiting): Node is currently in our recursion stack. If we see a1during our DFS, we have found a cycle!2(Visited): Node and all its descendants have been fully processed with no cycles.
def canFinish(numCourses, prerequisites):
# Build adjacency list
adj = [[] for _ in range(numCourses)]
for dest, src in prerequisites:
adj[src].append(dest)
# 0 = unvisited, 1 = visiting, 2 = visited
state = [0] * numCourses
def has_cycle(node):
if state[node] == 1: # Found a back-edge (cycle)
return True
if state[node] == 2: # Already cleared this path
return False
state[node] = 1 # Mark as visiting
for neighbor in adj[node]:
if has_cycle(neighbor):
return True
state[node] = 2 # Mark as fully visited
return False
# Graph might be disconnected, so check every node
for i in range(numCourses):
if state[i] == 0:
if has_cycle(i):
return False
return TrueComplexity:
- Time:
O(V + E)whereVis the number of courses (vertices) andEis the number of prerequisites (edges). - Space:
O(V + E)to store the adjacency list, plusO(V)for the recursion stack and state array.
Variations and pitfalls
- Disconnected Graphs: A common trap is assuming the graph is a single connected component. If the graph can be disconnected (like in the Course Schedule example), you must wrap your traversal in a loop that checks every node in the graph to ensure everything is visited.
- Recursion Limits: In Python, the default recursion limit is 1000. For a large graph (e.g., a 100x100 grid), a deep DFS will hit 10,000 calls and throw a
RecursionError. In an interview, mention that you would either usesys.setrecursionlimit()or convert the recursive DFS into an iterative DFS using an explicit Stack. - Bidirectional BFS: If you need to find the shortest path between a known start node and a known target node, searching from both ends simultaneously cuts the search space significantly. Instead of
O(B^D)(whereBis branching factor andDis distance), it becomesO(B^{D/2}).
Practice checklist
Ready to solidify these patterns? Try these problems on CureBugs:
- Flood Fill (Basic DFS/BFS)
- Word Ladder (Shortest Path BFS)
- Clone Graph (Graph Traversal with Hash Maps)
- Pacific Atlantic Water Flow (Multi-source DFS/BFS from edges)