The problem, in one line. Given a grid of land and water, count the separate islands, where land cells touching up, down, left or right belong to the same island. LeetCode 200.
The tell. “How many separate groups” on a grid. Counting groups of connected cells is counting connected components, and the tool is a walk that swallows a whole group at once.
The wrong first idea
Count the land cells.
return sum(row.count("1") for row in grid)
That counts cells, not islands. A block of four land cells is one island but scores four. The count you want goes up once per group, not once per cell.
The invariant
The full walkthrough is the clinic Clinic #15: Number of Islands. In short: scan every cell, and when you meet land you have not seen, that is a new island. Count it, then sink the whole island so you never meet it again.
flowchart LR A["scan finds fresh 1"] --> B["count += 1"] B --> C["sink every connected 1"] C --> A
The sentence that stays true every step: every land cell the scan reaches is either sunk already or belongs to an island not yet counted. Sinking the cell is the visited mark.
The solution
def num_islands(grid):
rows, cols = len(grid), len(grid[0])
def sink(r, c):
if 0 <= r < rows and 0 <= c < cols and grid[r][c] == "1":
grid[r][c] = "0" # sunk means visited
sink(r + 1, c)
sink(r - 1, c)
sink(r, c + 1)
sink(r, c - 1)
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1": # a fresh land cell starts a new island
count += 1
sink(r, c)
return count
print(num_islands([list("11000"), list("11000"), list("00100"), list("00011")]))
print(num_islands([list("101"), list("010"), list("101")]))
print(num_islands([list("000")]))
3
5
0
func numIslands(grid [][]byte) int {
rows, cols := len(grid), len(grid[0])
var sink func(r, c int)
sink = func(r, c int) {
if r >= 0 && r < rows && c >= 0 && c < cols && grid[r][c] == '1' {
grid[r][c] = '0' // sunk means visited
sink(r+1, c)
sink(r-1, c)
sink(r, c+1)
sink(r, c-1)
}
}
count := 0
for r := range grid {
for c := range grid[r] {
if grid[r][c] == '1' { // a fresh land cell starts a new island
count++
sink(r, c)
}
}
}
return count
}
Same three calls print 3, 5, 0.
Complexity
- Time O(m·n): the scan visits each cell once, and each land cell is sunk once.
- Space O(m·n): recursion can go as deep as the biggest island has cells.
Traps
- Counting diagonals as joined. The second call is a checkerboard of corner-touching land and the answer is 5, not 1.
- Forgetting to sink. Without the
"0"write, the walk bounces between two neighbours forever. - Comparing to the integer 1. The cells are the characters
"1"and"0", sogrid[r][c] == 1is never true and every grid answers 0.
Next in the ladder
Clone Graph keeps the walk and the visited mark, but the nodes are objects with neighbour lists, and you must build a copy of each one as you meet it.