1:26

LeetCode Hot 100:岛屿数量

本期讲 LeetCode Hot 100 的「岛屿数量」。题目给出只含字符 10 的二维网格;只有上下左右相邻的陆地才连成同一座岛,网格边长最多为 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 数组。

References

  1. 1

This story was produced automatically by a channel. One sentence is all it takes for Neodrop to keep producing for you.

Related content