Sub topic 6
Counting Islands: Components in a 2D Grid
This chapter assumes you already know how to label components with iterative DFS using an explicit stack, and that you can read Big-O bounds such as O(V + E). Here the same idea is applied to a grid. The grid itself is the graph, so you never build an adjacency list.
The Grid as an Implicit Graph
Consider a grid of characters where '1' is land and '0' is water. An island is a group of land cells joined horizontally or vertically. To count the islands, map the grid onto a graph:
- Each
'1'cell is a vertex. - Two land cells share an edge when they are next to each other in one of the four directions: up, down, left, or right.
- Water cells are not part of the graph.
With this mapping, an island is exactly a connected component. The neighbors of a cell (r, c) come from simple arithmetic, so you work them out as you go and store nothing. Filling a whole region outward from one starting cell is called flood fill.
The Algorithm
The outer loop plays the same role as looping over every vertex in graph labeling. Each land cell that is still unseen starts a new island. The inner loop is an iterative DFS that marks every land cell it can reach.
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)) # 3The 2×2 block in the top left is one island. The single cell at (2, 2) is the second. The pair at (3, 3) and (3, 4) is the third. The cell (2, 2) touches the other two islands only at their corners, so with four-directional neighbors it stands alone.
Cost
Let R be the number of rows and C the number of columns. Each cell is pushed at most once and checks four neighbors, so the time is O(R·C). The seen array uses O(R·C) space. In the worst case, a grid that is all land, the stack can also grow to O(R·C) entries. This matches the O(V + E) bound from graph traversal: V ≤ R·C, and each vertex has at most four edges, so E is O(R·C) too.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Marking a cell as seen when it is popped instead of when it is pushed | The same cell is pushed many times, which wastes time and memory | Set `seen` before `append` |
| Indexing the grid before checking bounds | `IndexError`, or silent wraparound at index `-1` | Test `0 <= ny < rows` first. Python's `and` stops at the first false test |
| Recursive flood fill on a large grid | `RecursionError` on big islands | Use an explicit stack, as shown |
| Calling it on an empty grid | `grid[0]` raises `IndexError` | Return 0 when `not grid` |
Exercise
Change the neighbor rule so that diagonally adjacent land cells also count as connected (8-directional). How many islands does the example grid have then, and what line of code changes?
Show answer
There is 1 island. Cell (1, 1) touches (2, 2) diagonally, and (2, 2) touches (3, 3) diagonally, so all land cells join into one component. Only the direction tuple changes. It becomes all eight offsets: ((1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)).
Exercise
Why does the outer loop need to check seen[r][c] and not only grid[r][c] == '1'?
Show answer
Without the check, every land cell would start a new count, even cells that an earlier flood fill already reached. The function would then return the number of land cells instead of the number of islands.