Sub topic 13
DFS on Grids: Flood Fill and Counting Islands
This chapter assumes you can already write recursive DFS over an adjacency list and that you know what a connected component is. Here you apply the same traversal to a 2D grid, where the graph is never built explicitly.
The grid as an implicit graph
In a grid problem, each cell is a vertex. Edges connect a cell to its neighbors, usually the four cells up, down, left, and right. You don't need an adjacency list because you can compute a cell's neighbors from its coordinates (r, c) whenever you need them.
Two checks replace the adjacency lookup:
- Bounds:
0 <= r < rowsand0 <= c < cols. - Membership: the cell has the value that belongs to the region, such as land
"1"or the original color.
Flood fill
Flood fill recolors every cell connected to a starting cell that shares its color. It works the same way as the paint-bucket tool in an image editor. Changing the color also works as the visited mark, so you don't need a separate set.
def flood_fill(image, sr, sc, new_color):
old = image[sr][sc]
if old == new_color:
return image # nothing to do; also prevents infinite recursion
rows, cols = len(image), len(image[0])
def visit(r, c):
if r < 0 or r >= rows or c < 0 or c >= cols:
return
if image[r][c] != old:
return
image[r][c] = new_color
visit(r + 1, c)
visit(r - 1, c)
visit(r, c + 1)
visit(r, c - 1)
visit(sr, sc)
return image
image = [[1, 1, 0], [1, 0, 0], [1, 1, 1]]
print(flood_fill(image, 0, 0, 2)) # [[2, 2, 0], [2, 0, 0], [2, 2, 2]]If old == new_color, recoloring a cell leaves it unchanged, so the cell still looks unvisited. Without the early return, the recursion would bounce between neighbors forever.
Counting islands
Counting islands is the connected-components loop from the previous chapter applied to a grid. Scan every cell. Each time you find land that you haven't seen yet, launch a DFS from it. That DFS floods exactly one island, so the number of launches equals the number of islands.
def count_islands(grid):
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
seen = set()
def visit(r, c):
if r < 0 or r >= rows or c < 0 or c >= cols:
return
if grid[r][c] != "1" or (r, c) in seen:
return
seen.add((r, c))
visit(r + 1, c)
visit(r - 1, c)
visit(r, c + 1)
visit(r, c - 1)
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1" and (r, c) not in seen:
visit(r, c)
islands += 1
return islands
grid = ["11000", "11000", "00100", "00011"]
print(count_islands(grid)) # 3Each cell is marked once and examined at most five times: once by the outer loop and once from each of its four neighbors. That makes the run time O(rows × cols), which is O(V + E) for a graph where every vertex has at most four edges.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Marking a cell after recursing instead of before | Infinite recursion or `RecursionError` | Mark a cell as soon as you enter it |
| Checking bounds after indexing | `IndexError`, or silent wraparound, because Python accepts `grid[-1]` | Test bounds first |
| Forgetting the `old == new_color` guard in flood fill | Infinite recursion | Return early |
| Mixing up rows and columns | Wrong regions, or errors on non-square grids | Use `r` with `rows` and `c` with `cols` consistently |
Exercise
If diagonal cells also count as neighbors (8-directional connectivity), how many islands does the example grid ["11000", "11000", "00100", "00011"] contain, and what change to visit produces that?
Show answer
One island. Cell (1,1) touches (2,2) diagonally, and (2,2) touches (3,3) diagonally, so all the land joins into one island. To get this result, add four recursive calls to visit: (r+1, c+1), (r+1, c-1), (r-1, c+1), and (r-1, c-1).
Exercise
In count_islands, what goes wrong if you remove the (r, c) not in seen check from the outer loop but keep the rest?
Show answer
Every land cell would add 1 to the count. When the outer loop reaches a cell that an earlier DFS already marked, visit returns at once, but islands += 1 still runs. The function would return the number of land cells (6 for the example grid) instead of the number of islands.