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.
Video lesson · Chapter 1 of 6
Where can the water reach?
Matrix depth-first search — The five-pixel octopus
1:06Reel
Read caption
Tess recolors an octopus made of five connected pixels. Watch the brush backtrack at a dead end and leave a diagonal mark untouched. Mark it. Go deep. Back up at a dead end.
How it works
Step through the idea, or press Play.
Read the grid as a graph. Each cell is a node; its four neighbours are edges, found with a direction array and a bounds check
Understand it
Start here
A grid is a graph in disguise
A map of land and water, a picture of pixels, a maze of walls: all are 2D grids. Treat each cell as a node and connect it to the cells directly above, below, left and right, and you have a graph. Nobody builds an adjacency list: the neighbours of are computed on the fly. That is why a grid is called an implicit graph.
How big is that graph?
Islands
Count groups of connected land, find the largest one, measure a perimeter.
Flood fill
The paint bucket tool: recolour every connected cell of the same colour.
Paths
Can you get from S to E through open cells? Solve a maze, check reachability.
Neighbours
Four directions and the bounds check
Moving up means row , down row , left column , right column . Store those four offsets in a list and loop over it, so you never write four nearly identical lines. Every neighbour must then pass the bounds check and before you read the grid.
DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)] # up, down, left, rightdef neighbours(grid, r, c): rows, cols = len(grid), len(grid[0]) for dr, dc in DIRS: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols: # bounds check first yield nr, ncgrid = [[1, 1, 0], [1, 0, 0], [0, 0, 1]]print(list(neighbours(grid, 0, 0))) # [(1, 0), (0, 1)]: a corner has 2print(list(neighbours(grid, 1, 1))) # [(0, 1), (2, 1), (1, 0), (1, 2)]: the centre has 4| Movement | Offsets | Neighbours | Used for |
|---|---|---|---|
| 4-directional | (-1,0) (1,0) (0,-1) (0,1) | up to 4 | Islands, flood fill, mazes: the default |
| 8-directional | the 4 above plus (-1,-1) (-1,1) (1,-1) (1,1) | up to 8 | When corners touch: Minesweeper, some image regions |
The template
Bounds, Valid, Mark, Recurse
One call of dfs(r, c)
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)]: dfs(grid, r + dr, c + dc, visited) # R: recursegrid = [[1, 1, 0], [1, 0, 0], [0, 0, 1]]seen = set()dfs(grid, 0, 0, seen)print(sorted(seen)) # [(0, 0), (0, 1), (1, 0)]: (2, 2) only touches at a corner- 1dfs(0,0)mark; up is out of bounds
- 2dfs(1,0)down: mark; all 4 neighbours rejected
- 3back in (0,0)left is out of bounds
- 4dfs(0,1)right: mark; all 4 neighbours rejected
- 5return3 cells visited, deepest stack 2
Every rejected call costs one check and returns at once. Only accepted cells add a frame that stays open.
Visited
Marking visited: in place or with a set
You need some record of which cells are done. Either keep a separate visited structure, or overwrite the cell itself: sink land 1 to 0, paint a pixel the new colour, or write a marker such as "#".
In place
- No extra set: saves memory.
- One check does double duty: a sunk cell looks like water.
- Destroys the input: copy first if the caller needs it.
- Natural for flood fill, where painting is the job.
Visited set or matrix
- Input stays untouched: safer in shared code.
- A
[[False] * C for _ in range(R)]matrix is faster than a set of tuples. - Costs extra memory.
- Needed when the grid is read-only or reused.
| Problem | Usual mark | Why |
|---|---|---|
| Number of islands | set grid[r][c] = "0" or a visited matrix | A sunk cell can never start another island |
| Flood fill | the new colour | A painted cell no longer matches the original colour |
| Max area of island | set to 0 | The DFS return value is the count; no set needed |
| Word Search (a backtracking cousin) | mark, then unmark on return | A cell may be reused by a different path |
Two ways
Recursive and iterative flood fill
Recursion keeps the cells waiting to be finished on the call stack. You can keep them on your own list instead: push the start, then repeatedly pop the newest cell, skip it if visited, mark it and push its valid neighbours. Popping the newest is last in, first out, a stack, so the walk is still depth-first.
def dfs_iterative(grid, sr, sc): rows, cols = len(grid), len(grid[0]) visited = set() stack = [(sr, sc)] while stack: r, c = stack.pop() # newest cell first: depth-first if (r, c) in visited: continue # was pushed twice: skip the copy visited.add((r, c)) for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols: if (nr, nc) not in visited and grid[nr][nc] == 1: stack.append((nr, nc)) return visitedgrid = [[1, 1, 0], [1, 1, 0], [0, 0, 0]]print(len(dfs_iterative(grid, 0, 0))) # 4The iterative loop
Iterative
- No recursion limit: safe on a 1000 × 1000 grid.
- Change one line to get BFS.
- Slightly more code.
Recursive
- Shortest and clearest: start here in interviews.
- Python stops at about 1,000 nested calls.
- Easy to return values up (area, True or False).
Pattern 1
Number of islands: count the DFS starts
Scan every cell in reading order. When the scan meets land that is not yet visited, it must be a new island, because every earlier island was visited completely by its own DFS. Count it, then run DFS to mark the whole island so the scan skips the rest of it.
Scan plus DFS
def num_islands(grid): rows, cols = len(grid), len(grid[0]) def sink(r, c): if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1": return grid[r][c] = "0" # mark by sinking sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1) islands = 0 for r in range(rows): for c in range(cols): if grid[r][c] == "1": sink(r, c) islands += 1 # once per DFS start return islandsgrid = [list("11000"), list("11000"), list("00100"), list("00011")]print(num_islands(grid)) # 3Pattern 2
Max area of island: return a count
Instead of returning nothing, let the DFS return how many cells it visited. A rejected cell (outside, water, already sunk) is worth 0; an accepted cell is worth 1 plus whatever its four neighbours bring back. The scan keeps the largest answer.
The area recurrence
def max_area(grid): rows, cols = len(grid), len(grid[0]) def area(r, c): if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 0: return 0 grid[r][c] = 0 # sink before recursing return (1 + area(r - 1, c) + area(r + 1, c) + area(r, c - 1) + area(r, c + 1)) best = 0 for r in range(rows): for c in range(cols): if grid[r][c] == 1: best = max(best, area(r, c)) return bestgrid = [[0, 1, 1, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [1, 1, 0, 0, 1]]print(max_area(grid)) # 4: islands of 3, 4 and 3Pattern 3
Flood fill and path existence
Flood fill recolours every cell connected to that has its original colour. The new colour is the visited mark, so no set is needed, with one trap: if the new colour equals the original, painted cells still match and DFS never ends. Path existence asks whether the end cell is reachable at all; DFS returns True on reaching it, and or stops the remaining directions from running.
dfs(r, c) for path existence
def flood_fill(image, sr, sc, color): original = image[sr][sc] if original == color: return image # guard against an endless loop def paint(r, c): if 0 <= r < len(image) and 0 <= c < len(image[0]) and image[r][c] == original: image[r][c] = color paint(r - 1, c); paint(r + 1, c); paint(r, c - 1); paint(r, c + 1) paint(sr, sc) return imagedef has_path(grid, start, end): # 0 = open, 1 = wall rows, cols, seen = len(grid), len(grid[0]), set() def dfs(r, c): if not (0 <= r < rows and 0 <= c < cols) or grid[r][c] == 1 or (r, c) in seen: return False if (r, c) == end: return True seen.add((r, c)) return dfs(r - 1, c) or dfs(r + 1, c) or dfs(r, c - 1) or dfs(r, c + 1) return dfs(*start)print(flood_fill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2)) # [[2, 2, 2], [2, 2, 0], [2, 0, 1]]maze = [[0, 0, 1, 0, 0], [1, 0, 1, 0, 1], [0, 0, 0, 0, 1], [0, 1, 1, 0, 0]]print(has_path(maze, (0, 0), (3, 4))) # Truemaze[3][3] = 1print(has_path(maze, (0, 0), (3, 4))) # FalseComplexity
O(R·C) time and space
Every cell is marked at most once. Each marked cell makes 4 calls, and every rejected call costs . The scan loop adds one look at each cell.
Time
Space, including recursion depth
| Approach | Time | Extra space (worst case) |
|---|---|---|
| Recursive DFS + visited set | set + stack | |
| Recursive DFS, sink in place | call stack | |
| Iterative DFS, explicit stack | list, no recursion limit | |
| BFS with a queue | bound; the frontier is often far smaller |
Python
The recursion limit
CPython allows about 1,000 nested calls by default. A 40 × 40 grid of solid land can already need more than that, and the result is RecursionError: maximum recursion depth exceeded. sys.setrecursionlimit raises the ceiling, but each Python frame also uses the C stack, so a large enough limit crashes the whole interpreter instead.
import sysdef sink_recursive(grid, r, c): if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == 1: grid[r][c] = 0 for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]: sink_recursive(grid, r + dr, c + dc)def sink_iterative(grid, r, c): stack = [(r, c)] while stack: r, c = stack.pop() if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == 1: grid[r][c] = 0 stack.extend([(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)])print("limit:", sys.getrecursionlimit())snake = [[1] * 3000] # one row of 3,000 land cellstry: sink_recursive([row[:] for row in snake], 0, 0) print("recursive: ok")except RecursionError: print("recursive: RecursionError")sink_iterative(snake, 0, 0)print("iterative: ok, cells left =", sum(snake[0])) # 0DFS or BFS
When to reach for BFS instead
Pick the grid traversal
Matrix DFS
- Recursion or a stack, goes deep first.
- Counting islands, flood fill, areas, any path.
- Less code: the recursion holds the state.
- Does not find shortest paths.
Matrix BFS
- A queue, spreads in rings.
- Shortest path in an unweighted grid, rotting oranges, distance to nearest.
- No recursion limit.
- See Matrix BFS.
Recap
Key takeaways
Key points
- A grid is an implicit graph: R·C nodes, edges to the up, down, left and right neighbours.
- Neighbours come from a direction array; check 0 ≤ r < R and 0 ≤ c < C before indexing, because Python's negative indexes wrap.
- Template: Bounds, Valid, Mark, Recurse. Mark before the recursive calls.
- Mark visited with a set or matrix, or in place by sinking or painting the cell.
- Number of islands = number of DFS starts in the scan. Max area: DFS returns 1 + its neighbours' areas.
- Flood fill: the new colour is the mark; return early if it equals the original.
- Path existence: DFS returns True at the end cell and or stops the search; it finds a path, not the shortest.
- O(R·C) time and O(R·C) space, including a call stack up to R·C deep. Use an explicit stack in Python for big grids.