Overview
Given an m × n 2D grid where "1" represents land and "0" represents water, count the number of distinct islands. An island is surrounded by water and is formed by connecting adjacent land cells horizontally or vertically.
Implement numIslands(grid).
Constraints
gridis a 2D array of strings ("0"or"1").1 ≤ m, n ≤ 300.- You may modify the grid in place (mark visited cells).
- Aim for $O(m \times n)$ time.
Examples
numIslands([ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ]); // → 1 numIslands([ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ]); // → 3
Notes
- Classic DFS/BFS flood-fill: iterate every cell. When you find a
"1", increment the count and flood-fill (mark all connected land as visited). - Mark visited cells by setting them to
"0"to avoid extra space for a visited set. - Alternatively, use Union-Find for a different approach.
Solution
Reveal solution
function numIslands(grid) {
if (!grid.length) return 0;
const rows = grid.length, cols = grid[0].length;
let count = 0;
function dfs(r, c) {
if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] === "0") return;
grid[r][c] = "0";
dfs(r + 1, c);
dfs(r - 1, c);
dfs(r, c + 1);
dfs(r, c - 1);
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === "1") {
count++;
dfs(r, c);
}
}
}
return count;
}Resources
count-islands-in-grid.js
Count Islands in a Grid
mediumcodingAlgorithmsGraphs
Overview
Given an m × n 2D grid where "1" represents land and "0" represents water, count the number of distinct islands. An island is surrounded by water and is formed by connecting adjacent land cells horizontally or vertically.
Implement numIslands(grid).
Constraints
gridis a 2D array of strings ("0"or"1").1 ≤ m, n ≤ 300.- You may modify the grid in place (mark visited cells).
- Aim for $O(m \times n)$ time.
Examples
numIslands([ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ]); // → 1 numIslands([ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ]); // → 3
Notes
- Classic DFS/BFS flood-fill: iterate every cell. When you find a
"1", increment the count and flood-fill (mark all connected land as visited). - Mark visited cells by setting them to
"0"to avoid extra space for a visited set. - Alternatively, use Union-Find for a different approach.
Solution
Reveal solution
function numIslands(grid) {
if (!grid.length) return 0;
const rows = grid.length, cols = grid[0].length;
let count = 0;
function dfs(r, c) {
if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] === "0") return;
grid[r][c] = "0";
dfs(r + 1, c);
dfs(r - 1, c);
dfs(r, c + 1);
dfs(r, c - 1);
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === "1") {
count++;
dfs(r, c);
}
}
}
return count;
}Resources
NameTopicDifficulty
103 of 103 problems