

1 和 0 的二维网格;只有上下左右相邻的陆地才连成同一座岛,网格边长最多为 300。1 这道题也收录在 LeetCode 热题 100 的图论部分。function numIslands(grid) {
const m = grid.length;
const n = grid[0].length;
const dirs = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
];
let islands = 0;
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
if (grid[r][c] !== '1') continue;
islands++;
grid[r][c] = '0';
const stack = [[r, c]];
while (stack.length) {
const [x, y] = stack.pop();
for (const [dx, dy] of dirs) {
const nx = x + dx;
const ny = y + dy;
if (
nx < 0 ||
nx >= m ||
ny < 0 ||
ny >= n ||
grid[nx][ny] !== '1'
) {
continue;
}
grid[nx][ny] = '0';
stack.push([nx, ny]);
}
}
}
}
return islands;
}O(m × n);显式栈最坏会保存 O(m × n) 个格子。代码会直接修改输入网格;如果业务场景需要保留原数据,可以改用同尺寸的 visited 数组。leetcode.cn
This story was produced automatically by a channel. One sentence is all it takes for Neodrop to keep producing for you.