Graphs: BFS and DFS
How to model a problem as a graph, the two ways to explore one, and the grid problems (islands, shortest path in a maze) that are secretly graphs.
In short
A graph is nodes and edges. BFS uses a queue and explores in rings: the first time it reaches a node is via a shortest path (unweighted). DFS uses a stack (or recursion) and dives deep. Both cost O(V + E). Always keep a visited set, or cycles will loop forever.
Modelling and representing a graph
Whenever something is connected to something else (cities and roads, people and friends, courses and prerequisites, cells in a grid), think graph. The usual representation is an adjacency list: for each node, the list of its neighbours.
| Representation | Space | Check an edge | List neighbours |
|---|---|---|---|
| Adjacency list | O(V + E) | O(degree) | O(degree) |
| Adjacency matrix | O(V²) | O(1) | O(V) |
Same graph, two orders
Switch between BFS and DFS and compare the visit order. The only change in the code is which end of the container you take from.
queue (leaves from the left)
visit order
1def bfs(graph, start):2 seen = {start}3 queue = deque([start])4 while queue:5 node = queue.popleft()6 for nb in graph[node]:7 if nb not in seen:8 seen.add(nb)9 queue.append(nb)
Variables
Which one to use
BFS
- Shortest path in an unweighted graph or grid
- Minimum number of steps / moves / mutations
- Level by level, multi-source (start from all sources at once)
- Memory: the widest ring
DFS
- Does a path exist? Connected components, flood fill
- Detect cycles, topological order
- Backtracking and exploring all possibilities
- Memory: the deepest path (recursion depth)
def num_islands(grid):
def sink(r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])) or grid[r][c] != '1':
return
grid[r][c] = '0' # mark visited
for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
sink(r + dr, c + dc)
count = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == '1':
count += 1; sink(r, c)
return countKey takeaways
- 01Model it as a graph: nodes, edges, adjacency list.
- 02BFS (queue) gives shortest paths in unweighted graphs; DFS (stack) explores and detects.
- 03Both are O(V + E) and need a visited set.
- 04A grid is a graph where each cell has up to four neighbours.
Check your understanding
1 of 3
Which finds the shortest path in an unweighted graph?
Related topics
Traversals
A tree is a node with up to two subtrees, so most problems are recursion: solve the left, solve the right, combine. DFS (inorder, preorder, postorder) uses the call stack; BFS (level order) uses a queue. All visit each node once: O(n); space is O(h) for DFS and O(width) for BFS.
9 min read →Stacks & queues
A stack gives back the most recent item first (LIFO); a queue gives back the oldest first (FIFO). Both do push and pop in O(1). Nested structure → stack. Processing in order of arrival → queue.
7 min read →