岛屿数量

默认 leetcode

原文

这个题自己想的解法:

  • 先找到所有1
  • 从第一个1开始拓展(搜索上下左右),拓展的同时做标记避免重复搜索
  • 对所有1执行拓展(有些1直接通过标记即可略过)

我觉得我这个实现方法应该性能很好,不知道为啥在leetcode上提交性能在后6%

var numIslands = function (grid) {
    let ones = [];
    const all = Array(grid.length + 2)
        .fill(0)
        .map(() => Array(grid[0].length + 2).fill(0));

    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[0].length; j++) {
            all[i + 1][j + 1] = Number(grid[i][j]);
            if (all[i + 1][j + 1] === 1) {
                ones.push([i + 1, j + 1]);
            }
        }
    }

    const islands = [];

    for (let i = 0; i < ones.length; i++) {
        let pos = ones[i];
        if (all[pos[0]][pos[1]] === 1) {
            islands.push(island(pos, all));
        }
    }

    return islands.length;
};

const island = (pos, grid) => {
    let a = 0;
    const land = [pos];
    let b = land.length;
    grid[pos[0]][pos[1]] = 0;
    while (a !== b) {
        for (let i = a, b = land.length; i < b; i++) {
            let [x, y] = land[i];
            if (grid[x - 1][y] === 1) {
                land.push([x - 1, y]);
                grid[x - 1][y] = 0;
            }
            if (grid[x][y - 1] === 1) {
                land.push([x, y - 1]);
                grid[x][y - 1] = 0;
            }
            if (grid[x + 1][y] === 1) {
                land.push([x + 1, y]);
                grid[x + 1][y] = 0;
            }
            if (grid[x][y + 1] === 1) {
                land.push([x, y + 1]);
                grid[x][y + 1] = 0;
            }
        }
        a = b;
        b = land.length;
    }
    return land;
};

上一篇 下一篇