Sub topic 13
DFS on Grids: Flood Fill and Counting Islands
Many problems arrive as a grid: a map of land and water, a bitmap image, a maze, or a game board. None of them looks like an adjacency list, but each one is a graph. This chapter shows how to run DFS on a grid without building a graph first. You will use it to count islands and to flood-fill regions. You will also see the grid-specific errors that come up most often.
This chapter assumes you know recursive and iterative DFS, the visited set, and how an outer loop over all vertices counts connected components. Those topics come from earlier chapters.
Seeing a Grid as a Graph
A grid with R rows and C columns is an implicit graph. That means you work out the edges when you need them instead of storing them.
- Vertices are cells, identified by a
(row, col)pair. - Edges join a cell to its neighbors. Usually the neighbors are the four cells up, down, left, and right. This is called 4-connectivity.
- Filtering removes cells you cannot enter: cells outside the grid, cells of the wrong type (water, walls, a different color), and cells you have already visited.
To get a cell's neighbors, add direction offsets to its coordinates. The adjacency list is never stored. The offsets play its role.
FOUR = [(1, 0), (-1, 0), (0, 1), (0, -1)]
EIGHT = FOUR + [(1, 1), (1, -1), (-1, 1), (-1, -1)]
def neighbors(r, c, rows, cols, directions=FOUR):
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
yield nr, nc
print(list(neighbors(0, 0, 3, 3))) # [(1, 0), (0, 1)]
print(len(list(neighbors(1, 1, 3, 3, EIGHT)))) # 8Whether diagonal cells count as neighbors is part of the problem statement. It is not something you get to choose. With 4-connectivity, two land cells that touch only at a corner are separate islands. With 8-connectivity, they are one island.
| Connectivity | Neighbors per cell | Typical use |
|---|---|---|
| 4-way | up to 4 | Island counting, paint-bucket fill, mazes with no diagonal moves |
| 8-way | up to 8 | Image blob detection, Minesweeper reveal, king moves on a board |
Counting Islands
An island is a maximal group of land cells ("1") joined through 4-way neighbors. In graph terms, each island is a connected component of the land cells. The outer loop goes over every cell. When it finds land that has not been seen yet, it starts one DFS. That DFS floods the whole island, so every cell it touches is skipped later. The number of DFS 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)) # 3The function visit checks its guards when a call starts. It does not check them before making a call. This "call first, check inside" style keeps the four recursive calls short and puts all the filtering in one place. The cost is extra calls that return immediately. The other style checks each neighbor before recursing. That style makes fewer calls, but you have to repeat the conditions or move them into a helper.
The order of the guards matters. The bounds check has to come before grid[r][c]. Python accepts negative indices, so grid[-1][c] quietly reads the last row instead of raising an error. Leave out the bounds check and a cell in the top row will "see" the bottom row as its upper neighbor. The result is wrong island counts with no error message.
Flood Fill with an Explicit Stack
Flood fill is the paint-bucket tool. You start at one cell and replace its color, plus the color of every connected cell with the same original color, with a new color. Here the grid itself records which cells have been visited: a recolored cell no longer matches the original color, so it will not be entered again.
The version below is iterative. Each cell is checked when it is popped from the stack, so the stack plays the role the call stack played above.
def flood_fill(image, sr, sc, new_color):
rows, cols = len(image), len(image[0])
old = image[sr][sc]
if old == new_color:
return image # nothing to do, and prevents an infinite loop
stack = [(sr, sc)]
while stack:
r, c = stack.pop()
if 0 <= r < rows and 0 <= c < cols and image[r][c] == old:
image[r][c] = new_color
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
stack.append((r + dr, c + dc))
return image
image = [[1, 1, 1],
[1, 1, 0],
[1, 0, 1]]
print(flood_fill(image, 1, 1, 2)) # [[2, 2, 2], [2, 2, 0], [2, 0, 1]]The cell in the bottom-right corner stays 1. It touches the filled region only at a corner, and this fill uses 4-way neighbors.
Recursion Depth on Grids
Grids are where recursive DFS most often fails in Python. The recursion depth can grow as large as the number of cells in a single region. A 300 by 300 grid that is all land has 90,000 cells. A winding path through that region can go far past CPython's default recursion limit of about 1000. The program then stops with RecursionError.
Your options, from most to least preferred:
- Use an explicit stack, as
flood_filldoes. Memory comes from the heap, and the only limit is the memory available. - Use BFS with a queue. For counting and filling, the order you visit cells does not matter, so BFS is just as correct.
- Raise the limit with
sys.setrecursionlimit. This is fragile. Very deep recursion can still crash the interpreter by overflowing the C stack, even after you raise the limit.
Complexity and Memory Choices
Every cell is marked at most once. Every marked cell looks at a fixed number of neighbors (4 or 8). Time is therefore O(R × C). This is the O(V + E) bound from earlier, because E is at most a constant times V on a grid.
Memory comes from two places:
| Component | Worst case | How to reduce it |
|---|---|---|
| Visited `seen` set | O(R × C) tuples | Mark the grid in place (overwrite `"1"` with `"0"`) or use a boolean matrix |
| Stack or call stack | O(R × C) | Check before pushing so fewer dead entries pile up |
Marking in place is the fastest choice and uses the least memory, but it destroys the input. If the caller still needs the original grid, copy it first or keep a separate visited matrix. Strings in Python are immutable, so to mark the island grid in place you first convert it to a list of lists: [list(row) for row in grid].
Common Errors
- Bounds checked after indexing, or not checked at all. Negative indices wrap around without any error.
- Marking a cell visited after its neighbors are explored instead of before. Cells already on the current path then get entered again, and the work can grow exponentially.
- Wrong connectivity. Using 8 directions when the problem says "horizontally or vertically," or the reverse.
- Assuming the grid is rectangular. Code that uses
len(grid[0])breaks on jagged input or an empty first row. Validate the input at the boundary. - Counting the wrong thing. The island count goes up once per launch from the outer loop, never inside
visit.
Exercise
Run count_islands on grid = ["11000", "11000", "00100", "00011"] but with 8-way connectivity (diagonals count). How many islands are there, and why?
Show answer
One. Cell (1,1) touches (2,2) diagonally, and (2,2) touches (3,3) diagonally, so all three 4-way islands merge into a single 8-way component.
Exercise
Modify the island idea to return the area of the largest island. Where does the area get counted, and what changes in the outer loop?
Show answer
Have visit return 1 plus the sum of its four recursive calls, and return 0 from every guard. In the outer loop, replace islands += 1 with best = max(best, visit(r, c)) and return best. Area is counted once per newly marked cell, inside visit.
Exercise
In floodfill, what happens if you call floodfill(image, 0, 0, 1) on an image whose cell (0, 0) is already 1, with the early-return guard removed?
Show answer
It never terminates. Recolored cells still equal old, so every cell keeps being pushed and repainted, and the stack never empties. The guard returns immediately because the fill would change nothing.