Skip to main content

Number of Islands (DFS/BFS)

Given an $m \times n$ 2D binary grid grid representing a map of '1's (land) and '0's (water), return the total number of islands. An island is formed by connecting adjacent lands horizontally or vertically. You may assume the entire grid is surrounded by water.

Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1

Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
function numIslands(grid) {
if (!grid || grid.length === 0) {
return 0;
}

const rows = grid.length;
const cols = grid[0].length;
let islandCount = 0;

// DFS helper function to sink the current island by marking '1's as '0's
const sinkIsland = (r, c) => {
// Base case: check boundaries or if it's water ('0')
if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] === '0') {
return;
}

// Mark the current land cell as visited (change '1' to '0')
grid[r][c] = '0';

// Recurse in all four adjacent directions (up, down, left, right)
sinkIsland(r + 1, c);
sinkIsland(r - 1, c);
sinkIsland(r, c + 1);
sinkIsland(r, c - 1);
};

for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === '1') {
// Found the start of a new, uncounted island
islandCount++;
// Explore and mark the entire connected component (island)
sinkIsland(r, c);
}
}
}

return islandCount;
}