24. Number of Islands
Given an $m \times n$ 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
How It Works & Algorithmic Design
Solves using Grid Graph Exploration (DFS/BFS):
- Grid Traversal: Loop through every cell
grid[r][c]. - Land Discovered: When
grid[r][c] === '1':- Increment
islandCount++. - Launch
sinkIsland(r, c)(DFS/BFS) to visit all connected land cells in 4 directions (up, down, left, right) and mark them as'0'(water) to prevent double counting.
- Increment
- Return:
islandCountafter scanning all grid cells.
Why This Approach Works Best
Sinking land cells in-place eliminates extra visited array memory, exploring the grid in $O(m \times n)$ time and $O(m \times n)$ recursion stack space.
Example Walkthrough
[["1","1","0"],["1","1","0"],["0","0","1"]]
2D land map.
Island 1 at (0,0) sinks connected land at (0,1),(1,0),(1,1). Island 2 found at (2,2).
Counts connected components.
2
Total 2 islands.
Answer: Number of Islands using Grid DFS
function numIslands(grid) {
if (!grid || grid.length === 0) return 0;
let count = 0;
function dfs(r, c) {
if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || 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 < grid.length; r++) {
for (let c = 0; c < grid[0].length; c++) {
if (grid[r][c] === '1') {
count++;
dfs(r, c);
}
}
}
return count;
}Traverse grid cells and sink connected land areas using recursive DFS traversal.
Modifying grid cells to '0' acts as an in-place visited set.
Explores all connected land components in 4 directional directions.
Runs in $O(m \times n)$ time.