Number of islands
Medium TimeO(n·m) SpaceO(n·m)
A grid holds 1 for land and 0 for water, and an island is a group of 1s joined horizontally or vertically — land touching only at a corner counts as separate. Given grid, return how many islands it contains. A grid of all water has none.
Examples
Example 1
- Input
- grid = [[1, 1, 0], [0, 1, 0], [0, 0, 1]]
- Output
- Three
21s joined into one island, and the corner1touching only diagonally is a second.
Example 2
- Input
- grid = [[0, 0], [0, 0]]
- Output
- All water, so there is no island to count.
0
The Code
function numIslands(grid) {
let count = 0;
function sink(r, c) {
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) return;
if (grid[r][c] !== 1) return;
grid[r][c] = 0;
sink(r + 1, c);
sink(r - 1, c);
sink(r, c + 1);
sink(r, c - 1);
}
for (let r = 0; r < grid.length; r++) {
for (let c = 0; c < grid[0].length; c++) {
if (grid[r][c] === 1) {
count++;
sink(r, c);
}
}
}
return count;
}
numIslands([[1, 1, 0], [0, 1, 0], [0, 0, 1]]);Done
The first 27 calls, of 35. This one does not fit on a page.
More like this
All matrices & grids examples (7) →- Spiral order Four shrinking boundaries peel the grid one ring at a time.
- Rotate a matrix Transpose, then mirror each row — a rotation in two easy passes.
- Transpose Rows become columns — read down instead of across.
- Flood fill The paint-bucket tool — recurse outwards while the colour matches.
- Set matrix zeroes Record which rows and columns to blank before blanking anything.
- Maximal rectangle Every row is a histogram — solve that, then sweep downwards.