Sub topic 6
Counting Islands: Components in a 2D Grid
This chapter assumes you have read the earlier chapters on adjacency lists, BFS labeling, and iterative DFS labeling. You should be comfortable with a seen array, an explicit stack, and collections.deque. The goal here is to apply the same component-finding idea to a grid, where the graph is never built explicitly.
The Grid Is Already a Graph
Many real problems arrive as a 2D array instead of an edge list. Examples include a satellite image of land and water, a game map of walls and floor, or a bitmap where you want to find blobs of the same color. The classic version is the "number of islands" problem. You get a grid of '1' (land) and '0' (water) cells, and you must count the groups of land cells that touch each other.
This is a connected components problem. The mapping is direct:
| Graph concept | Grid equivalent |
|---|---|
| Vertex | A cell `(row, col)` whose value is `'1'` |
| Edge | Two land cells that are horizontal or vertical neighbors |
| Adjacency list of `u` | The up to 4 in-bounds land neighbors of a cell, computed on demand |
| Connected component | An island |
| Number of components | Number of islands |
The key difference from earlier chapters is that you never build adj. Each cell's neighbors come from arithmetic: add (1, 0), (-1, 0), (0, 1), and (0, -1) to its coordinates, then throw away anything out of bounds or not land. People call this an implicit graph. Traversing it to mark one region is called flood fill, after the paint-bucket tool in image editors.
Flood Fill with an Explicit Stack
The structure matches components_dfs from the iterative DFS chapter. An outer loop scans every cell. Each time it finds land that has not been seen, it counts a new island and floods outward from there.
def count_islands(grid):
rows, cols = len(grid), len(grid[0])
seen = [[False] * cols for _ in range(rows)]
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != '1' or seen[r][c]:
continue
count += 1
seen[r][c] = True
stack = [(r, c)]
while stack:
y, x = stack.pop()
for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
ny, nx = y + dy, x + dx
if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == '1' and not seen[ny][nx]:
seen[ny][nx] = True
stack.append((ny, nx))
return count
grid = [
"11000",
"11000",
"00100",
"00011",
]
print(count_islands(grid)) # 3Here is how the example works out. The scan hits (0, 0) first, counts island 1, and the fill marks the 2×2 block in the top left. The scan skips those cells because they are seen. At (2, 2) it finds new land and counts island 2, which is a single cell. At (3, 3) it counts island 3, and the fill also picks up (3, 4). Cell (2, 2) touches the other islands only at corners, so with 4-directional neighbors it forms an island of its own.
Why the bounds check comes first
The condition 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == '1' relies on short-circuit evaluation. If the bounds test fails, Python never reads grid[ny][nx]. Order matters for a subtle reason. A negative index such as grid[-1] does not raise an error in Python. It silently wraps to the last row. If you indexed first and checked bounds afterward, a cell on the top edge would "see" a neighbor on the bottom edge, and islands on opposite edges could merge.
Mark on push, not on pop
The code sets seen[ny][nx] = True at the moment it pushes a neighbor, not when it pops it. If you marked on pop, a cell with several land neighbors could be pushed several times before it is processed. The answer would still be correct, but the stack could grow to hold duplicates. In a large solid block of land, that wastes a lot of memory. Marking on push guarantees each cell enters the stack at most once. The BFS chapter used the same rule for the same reason.
Variations You Will Meet
BFS, island sizes, and diagonal neighbors
Swapping the stack for a deque turns this into BFS. The island count stays the same, only the visiting order changes. The version below also records each island's size and accepts an option for 8-directional connectivity, where diagonal neighbors count as touching. It also handles an empty grid, which count_islands does not: grid[0] raises IndexError when grid == [].
from collections import deque
def island_sizes(grid, diagonal=False):
if not grid or not grid[0]:
return []
rows, cols = len(grid), len(grid[0])
if diagonal:
steps = [(dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1) if (dy, dx) != (0, 0)]
else:
steps = [(1, 0), (-1, 0), (0, 1), (0, -1)]
seen = [[False] * cols for _ in range(rows)]
sizes = []
for r in range(rows):
for c in range(cols):
if grid[r][c] != '1' or seen[r][c]:
continue
seen[r][c] = True
queue = deque([(r, c)])
size = 0
while queue:
y, x = queue.popleft()
size += 1
for dy, dx in steps:
ny, nx = y + dy, x + dx
if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == '1' and not seen[ny][nx]:
seen[ny][nx] = True
queue.append((ny, nx))
sizes.append(size)
return sizes
grid = [
"11000",
"11000",
"00100",
"00011",
]
print(island_sizes(grid)) # [4, 1, 2]
print(island_sizes(grid, diagonal=True)) # [7]With diagonals allowed, (1, 1) touches (2, 2), and (2, 2) touches (3, 3), so the whole grid becomes one island of 7 cells. Which rule is right depends on the problem. Image processing calls these 4-connectivity and 8-connectivity, and the problem statement decides which one applies. Read it carefully.
Overwriting the grid instead of keeping `seen`
A common space saving is to sink each visited land cell by overwriting it with '0', which removes the need for a separate seen array. Python strings are immutable, so you first need a mutable copy:
def count_islands_sinking(grid):
if not grid or not grid[0]:
return 0
g = [list(row) for row in grid]
rows, cols = len(g), len(g[0])
count = 0
for r in range(rows):
for c in range(cols):
if g[r][c] != '1':
continue
count += 1
g[r][c] = '0'
stack = [(r, c)]
while stack:
y, x = stack.pop()
for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
ny, nx = y + dy, x + dx
if 0 <= ny < rows and 0 <= nx < cols and g[ny][nx] == '1':
g[ny][nx] = '0'
stack.append((ny, nx))
return count
print(count_islands_sinking(["11000", "11000", "00100", "00011"])) # 3The copy costs the same O(R·C) memory as seen, so here the trick saves nothing. It pays off only when the caller hands you a mutable grid and agrees to let you destroy it. Mutating the caller's data without permission causes bugs in whatever code reads that grid next.
Cost of Flood Fill
Let R be the number of rows and C the number of columns. The grid has V = R·C potential vertices and at most 4 edges per vertex (8 with diagonals), so E = O(R·C). The O(V + E) bound from the complexity chapter therefore becomes O(R·C) time.
Counting the work directly gives the same answer. The outer scan touches each cell once. Each land cell is pushed and popped once, because marking on push prevents duplicates, and each pop checks a fixed number of neighbors.
Space is O(R·C) for seen. The stack also needs space. For DFS it can hold O(R·C) cells in the worst case, such as a snake-shaped island. For BFS the queue holds roughly one "frontier" at a time, which is often closer to O(R + C) on open regions. Worst cases can still be larger.
| Approach | Extra memory | Mutates input | Recursion risk |
|---|---|---|---|
| Stack + `seen` | O(R·C) | No | None |
| Queue (BFS) + `seen` | O(R·C) | No | None |
| Sinking a copy | O(R·C) | No | None |
| Sinking in place | Stack only | Yes | None |
| Recursive DFS | O(R·C) call stack | Optional | High |
If the grid changes over time, for example when cells turn from water to land one at a time, rerunning flood fill after each change costs O(R·C) per update. The union-find chapters that follow handle that case much more cheaply. You treat each cell as a set and union it with its land neighbors when it appears.
Exercise
Using the 4×5 example grid, how many islands are there with 4-directional connectivity, and how many with 8-directional connectivity? Explain which cells cause the difference.
Show answer
There are 3 islands with 4-directional connectivity and 1 with 8-directional connectivity. Cell (2, 2) touches (1, 1) and (3, 3) only diagonally. With diagonals allowed, it links the top-left block, itself, and the bottom-right pair into a single island of 7 cells.
Exercise
A teammate moves the line seen[ny][nx] = True so that it runs right after y, x = stack.pop(), setting seen[y][x] = True there instead. Is the island count still correct? What changes?
Show answer
The count stays correct as long as popped cells that are already seen get skipped, because every reachable cell is still visited before the outer scan moves on. However, a cell can now be pushed once for each land neighbor that discovers it before it is popped, so the stack can hold duplicates and use far more memory on dense land. Marking on push keeps each cell on the stack at most once.
Exercise
Write a function largest_island(grid) that returns the number of cells in the biggest 4-connected island, or 0 if there is no land. Reuse an existing function from this chapter.
Show answer
def largest_island(grid): return max(island_sizes(grid), default=0). For the example grid it returns 4. The default=0 handles grids with no land and the empty grid, since island_sizes returns an empty list in both cases.
Exercise
Why does count_islands check 0 <= ny explicitly instead of relying on Python to raise an IndexError when ny is -1?
Show answer
Python treats negative indices as offsets from the end, so grid[-1] returns the last row instead of raising an error. Without the explicit check, cells on the top edge would see the bottom row as neighbors (and the left edge would see the right column), which can merge separate islands and produce a wrong count.