← All posts
postApril 13, 2026
Count Islands (Matrix DFS)
#javascript#graph#dfs#algorithms#matrix
Hard⏱️ Logic Challenge
Given a 2D grid of '1' (land) and '0' (water), count the number of islands. An island is formed by connecting adjacent lands horizontally or vertically.
Ver solución
function numIslands(grid) {
let count = 0;
function dfs(r, c) {
if (r < 0 || r >= grid.length ||
c < 0 || c >= grid[0].length ||
grid[r][c] !== '1') return;
grid[r][c] = '0'; // mark visited
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') {
dfs(r, c);
count++;
}
}
}
return count;
}
// When we find a '1', flood-fill the whole island with '0' (DFS).
// Each flood-fill = 1 island.