Last Commit: 2024-01-06 17:50:27

views:

200. Number of Islands

source: https://leetcode.com/problems/number-of-islands/

Question

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

dfs

这题比较直接的想法就是dfs,把已统计的点沉没。

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
    let ret = 0;
    const sink = (x, y) => {
        // y轴越界
        if (y < 0 || y >= grid.length) return;
        // x轴越界
        if (x < 0 || x >= grid[y].length) return;
        // 已经是非岛屿地区
        if (grid[y][x] === '0') return;
        // 沉没此点
        grid[y][x] = '0';
        // dfs上下左右四个点
        sink(x + 1, y);
        sink(x - 1, y);
        sink(x, y + 1);
        sink(x, y - 1);
    };
    for (let y = 0; y < grid.length; y++) {
        for (let x = 0; x < grid[y].length; x++) {
            if (grid[y][x] === '1') {
                ret += 1;
                sink(x, y);
            }
        }
    }
    return ret;
};

bfs

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
    let ret = 0;
    const queue = [];
    for (let y = 0; y < grid.length; y++) {
        for (let x = 0; x < grid[y].length; x++) {
            if (grid[y][x] === '1') {
                ret += 1;
                grid[y][x] = '0';
                queue.push([y, x]);
                while (queue.length) {
                    const [y, x] = queue.shift();
                    [[y - 1, x], [y + 1, x], [y, x - 1], [y, x + 1]].filter(([y, x]) => grid[y]?.[x] === '1').forEach(([y, x]) => {
                        grid[y][x] = '0';
                        queue.push([y, x]);
                    });
                }
            }

        }
    }
    return ret;
};

并查集

总结