[leetcode刷题记录] 1254.统计封闭岛屿数量

原题链接:1254. 统计封闭岛屿的数目 - 力扣(LeetCode) (leetcode-cn.com)
考察知识点: dfs
解题思路与源代码:

/**
 * @param {number[][]} grid
 * @return {number}
 */

var closedIsland = function(grid) {
    // isBorder为是否超出边界 , resCount为封闭岛屿数量
    let isBorder = 0, resCount = 0;
    // 判断是否超界
    const isArea = (grid, row, col) => {
        if(row<0 || row>=grid.length || col<0 || col>=grid[0].length){
            return false
        }
        return true;
    }
    //dfs深度优先算法
    const dfsArea = (grid, row, col)=> {
        if (!isArea(grid, row, col)){
            isBorder++;
            return;
        }
        //如果不是陆地或者已经遍历过停止该方向遍历
        if(grid[row][col] != 0){
            return;
        }
        //遍历过后,记录已遍历标记为2
        grid[row][col] = 2;
        //四个方向进行遍历
        dfsArea(grid, row-1, col);
        dfsArea(grid, row, col+1);
        dfsArea(grid, row+1, col);
        dfsArea(grid, row, col-1);
    }

    for (let i=0; i

你可能感兴趣的:([leetcode刷题记录] 1254.统计封闭岛屿数量)