Matrix DFS
medium 20 minA 2D grid is a graph in disguise: every cell is a node and its up, down, left and right neighbours are its edges.
See it run
Treat every cell as a node and its four neighbours as edges, then dive deep: check bounds, check valid, mark, recurse.
Operations
Recursive DFS from one cell
Start at (0,0) on a 3×3 grid of land (1) and water (0) and visit every land cell connected to it, going as deep as possible in one direction before backing up. Directions are tried up, down, left, right.
Step 1 of 8
A grid is a graph
| 0 | 1 | 2 | |
|---|---|---|---|
| 0 | 1 | 1 | 0 |
| 1 | 1 | 0 | 0 |
| 2 | 0 | 0 | 1 |
call stack: empty · visited: 0
Each cell is a node; its up, down, left and right neighbours are its edges. Land is 1, water is 0 (faded). We call dfs(grid, 0, 0, visited) with an empty visited set.
Step 1: A grid is a graph
def dfs(grid, r, c, visited): rows, cols = len(grid), len(grid[0]) if r < 0 or r >= rows or c < 0 or c >= cols: # B: bounds return if (r, c) in visited or grid[r][c] == 0: # V: valid? return visited.add((r, c)) # M: mark for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # R: up, down, left, right dfs(grid, r + dr, c + dc, visited)grid = [[1, 1, 0], [1, 0, 0], [0, 0, 1]]visited = set()dfs(grid, 0, 0, visited)print(sorted(visited)) # [(0, 0), (0, 1), (1, 0)]- Time
- O(R·C)
- Space
- O(R·C)
- per cell
- 4 neighbour checks
- call depth
- up to R·C
The direction order changes the path DFS takes, never the set of cells it ends up visiting.
In the real world
The same matrix dfs doing real jobs. Pick one and step through it.
Water breaks in at the valley's west gap and spreads to every connected patch of land. Mountains (▲) block it. A recursive DFS flood rushes down one channel before filling the next, and its call stack gets very deep.
Step 1 of 5
Breach at (2,0)
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|---|
| 0 | ▲ | ▲ | ▲ | ▲ | ▲ | ▲ | ▲ | ▲ |
| 1 | ▲ | H | F | ▲ | ||||
| 2 | ||||||||
| 3 | ▲ | F | H | ▲ | H | ▲ | ||
| 4 | ▲ | ▲ | ▲ | ▲ | ||||
| 5 | ▲ | ▲ | ▲ | ▲ | ▲ | ▲ | ▲ | ▲ |
flooded: 0 · houses: 0 · farms: 0
A 6×8 valley ringed by mountains, with an open gap on the west edge at (2,0). H is a house, F is a farm. The flood is a DFS from the breach.
Step 1: Breach at (2,0)
def flood(terrain, r, c): if r < 0 or r >= len(terrain) or c < 0 or c >= len(terrain[0]): return if terrain[r][c] in ("^", "~"): # mountain, or already flooded return terrain[r][c] = "~" # flood it for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]: flood(terrain, r + dr, c + dc)Common mistakes
The bugs interviewers watch for, with the fix beside each.
Indexing before the bounds check
criticalIn Python
grid[-1][c]does not raise: it reads the last row, so DFS silently wraps around the edge and joins land on opposite sides. Past the far edge it raises IndexError. Check0 <= r < rows and 0 <= c < colsfirst, and letorshort-circuit before the grid is touched.Wrongdef dfs(r, c): if grid[r][c] == "0" or r < 0 or r >= rows: # reads grid[-1] first returnRightdef dfs(r, c): if r < 0 or r >= rows or c < 0 or c >= cols: # bounds first return if grid[r][c] == "0": returnMarking visited after recursing
criticalTwo land cells side by side call each other forever if neither is marked until its calls return: (0,0) → (0,1) → (0,0) → … until RecursionError. Mark the cell the moment you accept it, before any recursive call.
Wrongdef dfs(r, c): ... for dr, dc in DIRS: dfs(r + dr, c + dc) visited.add((r, c)) # too lateRightdef dfs(r, c): ... visited.add((r, c)) # mark first for dr, dc in DIRS: dfs(r + dr, c + dc)Flood fill with the same colour
majorWhen the new colour equals the original, a painted cell still matches
original, so painting does not work as a visited mark and DFS bounces between neighbours forever. Return early.Wrongdef flood_fill(image, sr, sc, color): original = image[sr][sc] dfs(sr, sc) # loops if color == original return imageRightdef flood_fill(image, sr, sc, color): original = image[sr][sc] if original == color: return image dfs(sr, sc) return imageCounting inside the DFS
majorIncrementing the island counter inside
dfscounts land cells, not islands. The count belongs in the scan loop, once per DFS start.Wrongdef dfs(r, c): nonlocal islands ... visited.add((r, c)) islands += 1 # counts every cellRightfor r in range(rows): for c in range(cols): if grid[r][c] == "1" and (r, c) not in visited: dfs(r, c) islands += 1 # once per islandSwapping rows and columns
minorOn a non-square grid, using
len(grid)for both bounds either misses columns or walks off the end. Rows arelen(grid), columns arelen(grid[0]), and every cell isgrid[r][c], row first.Wrongn = len(grid)if r < 0 or r >= n or c < 0 or c >= n: # wrong when rows != cols returnRightrows, cols = len(grid), len(grid[0])if r < 0 or r >= rows or c < 0 or c >= cols: returnDeep recursion on a big grid
majorOne island can be R·C cells long. A 100×100 all-land grid can need thousands of nested calls, and Python stops at about 1,000 with RecursionError. Use an explicit stack (or raise the limit, which only helps until the C stack runs out).
Wrongdfs(0, 0) # RecursionError on a 300 x 300 block of landRightstack = [(0, 0)]while stack: r, c = stack.pop() ... # same checks, push neighbours instead of recursing
Interview tips
How to explain it
- A grid is an implicit graph: each cell is a node, its four neighbours are its edges. No adjacency list needed.
- DFS: check bounds, check the cell is valid, mark it, recurse in four directions.
- Each cell is marked once and checks 4 neighbours: O(R·C) time. Visited plus the call stack: O(R·C) space.
Spot it in problems
- Count regions, islands or components in a grid: scan plus DFS, count each DFS start.
- Size of the largest region: DFS returns 1 + the sum of its neighbours.
- Repaint or capture a connected region (flood fill, surrounded regions): DFS from the seed or from the border.
- Can I get from A to B at all: DFS returning a boolean. Fewest steps: switch to BFS.
Memory tricks
- BVMR: Bounds, Valid, Mark, Recurse, in that order every time.
- Up, down, left, right is (-1,0), (1,0), (0,-1), (0,1): the row moves first, then the column.
- A painted or sunk cell is a visited cell.
Watch out
- Negative indexes wrap in Python: bounds check before you touch the grid.
- Mark before recursing, never after.
- In-place marking saves the visited set, not the call stack: worst case is still O(R·C).
- Big grids and recursion do not mix in Python: go iterative.