Boss lesson · Unit 02
Count the islands
One flood fill per connected component
What you practise
- Connected components by flood fill
Try a question from this lesson
Pick one
A 1 is land and a 0 is water. Land cells that touch up, down, left or right belong to the same island. How many islands are in this grid?
grid = [
[1, 1, 0, 0],
[1, 0, 0, 1],
[0, 0, 0, 1],
[1, 0, 0, 0],
]const grid = [
[1, 1, 0, 0],
[1, 0, 0, 1],
[0, 0, 0, 1],
[1, 0, 0, 0],
];const grid: number[][] = [
[1, 1, 0, 0],
[1, 0, 0, 1],
[0, 0, 0, 1],
[1, 0, 0, 0],
];Correct answer
3
Why
Three: the L-shape in the top-left, the pair on the right edge, and the single cell in the bottom-left. Six is the number of land cells. An island is a group of connected nodes: a connected component.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Flood fill
To remove one island, start on any of its cells and run a depth-first search that turns every land cell it reaches into water.
Each call first stops if it is off the grid or on water. Otherwise it sinks its own cell and tries all four neighbours.
def sink(grid, r, c):
if not (0 <= r < len(grid)):
return
if not (0 <= c < len(grid[0])):
return
if grid[r][c] != 1:
return
grid[r][c] = 0
sink(grid, r + 1, c)
sink(grid, r - 1, c)
sink(grid, r, c + 1)
sink(grid, r, c - 1)function sink(grid, r, c) {
// stop: off the grid, or water
if (grid[r]?.[c] !== 1) return;
grid[r][c] = 0;
sink(grid, r + 1, c);
sink(grid, r - 1, c);
sink(grid, r, c + 1);
sink(grid, r, c - 1);
}function sink(
grid: number[][],
r: number,
c: number,
): void {
// stop: off the grid, or water
if (grid[r]?.[c] !== 1) return;
grid[r][c] = 0;
sink(grid, r + 1, c);
sink(grid, r - 1, c);
sink(grid, r, c + 1);
sink(grid, r, c - 1);
}Python noteThe bounds checks must come first. grid[-1] does not fail in Python: it silently reads the last row.
JavaScript notegrid[r]?.[c] is undefined for any cell off the grid instead of an error, so one test covers the bounds and the water.
TypeScript notegrid[r]?.[c] is undefined for any cell off the grid instead of an error, so one test covers the bounds and the water.
9 more exercises in the app
- 2× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.