Sub topic 10
Flood fill and counting regions
This chapter assumes you can write the neighbors function from the earlier chapter and that you know how a stack works. Here you will use the same grid graph to answer a different question: how many separate areas does it contain?
From shortest paths to regions
Breadth-first search finds the fewest steps between two cells. Sometimes you don't need a path. You only need to know which cells can reach each other. A set of cells that can all reach each other, and can reach nothing else, is a connected component. On a grid, people usually call it a region.
Flood fill starts at one cell and visits every cell reachable from it. Think of pouring paint on that cell and letting it spread until walls stop it. To count regions, you run a flood fill from each open cell that no earlier fill has reached. The number of fills you start equals the number of regions.
The algorithm
- Keep a
seenset of cells already assigned to a region. - Scan every cell in row-major order.
- Skip walls and cells already in
seen. - Otherwise, add 1 to the count and flood fill from that cell, adding each reached cell to
seen.
The code
This version uses an explicit stack instead of recursion. A recursive fill on a large open grid can exceed Python's recursion limit.
def neighbors(grid, r, c, diagonal=False):
steps = [(-1, 0), (1, 0), (0, -1), (0, 1)]
if diagonal:
steps += [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for dr, dc in steps:
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != '#':
yield nr, nc
def count_regions(grid):
rows, cols = len(grid), len(grid[0])
seen = set()
regions = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == '#' or (r, c) in seen:
continue
regions += 1
seen.add((r, c))
stack = [(r, c)]
while stack:
cell = stack.pop()
for nxt in neighbors(grid, *cell):
if nxt not in seen:
seen.add(nxt)
stack.append(nxt)
return regions
grid = [
"..#..",
"..#..",
"###..",
"#.#..",
]
print(count_regions(grid))This prints 3. The regions are the top-left block, the right-hand block, and the single open cell at row 3, column 1, which is walled in on all sides.
Why it works
Each cell is added to seen once and popped from the stack once, so the work is proportional to the number of cells times the number of directions. The outer scan adds only one visit per cell. The fill order does not matter for counting. A stack gives depth-first order, and a queue would give breadth-first order. Both reach the same set of cells.
Common errors
- Marking cells seen on pop instead of on push. The same cell can then sit on the stack many times. The count stays correct, but the work grows.
- Forgetting to share
seenacross fills. If you reset it for every fill, you will count the same region many times. - Counting walls. Check for
'#'before starting a fill, as the scan does. - Ignoring connectivity. With
diagonal=True, regions that touch only at a corner merge. Decide which rule the problem uses before you count.
Exercise
Consider the grid ["..#", ".#.", "#.."]. How many regions does count_regions report with 4-direction movement, and how many with 8-direction movement (passing diagonal=True to neighbors)?
Show answer
With 4-direction movement there are 2 regions: {(0,0), (0,1), (1,0)} and {(1,2), (2,1), (2,2)}. With 8-direction movement there is 1 region, because (0,1) and (1,2) touch diagonally and both are open.