LeetCode //C - 1254. Number of Closed Islands

1254. Number of Closed Islands

Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.

Return the number of closed islands.

Example 1:

Input: grid = \[1,1,1,1,1,1,1,0,1,0,0,0,0,1,1,0,1,0,1,0,1,1,1,0,1,0,0,0,0,1,0,1,1,1,1,1,1,1,1,0]

Output: 2

Explanation:

Islands in gray are closed because they are completely surrounded by water (group of 1s).

Example 2:

Input: grid = \[0,0,1,0,0,0,1,0,1,0,0,1,1,1,0]

Output: 1

Example 3:

Input: grid = \[1,1,1,1,1,1,1,

1,0,0,0,0,0,1,

1,0,1,1,1,0,1,

1,0,1,0,1,0,1,

1,0,1,1,1,0,1,

1,0,0,0,0,0,1,

1,1,1,1,1,1,1\]

Output: 2

Constraints:
  • 1 <= grid.length, grid0.length <= 100
  • 0 <= gridij <=1

From: LeetCode

Link: 1254. Number of Closed Islands


Solution:

Ideas:

first flood-fill all land touching the border, because it cannot be closed. Then count the remaining land groups.

Code:
c 复制代码
void dfs(int** grid, int r, int c, int m, int n) {
    if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] == 1)
        return;

    grid[r][c] = 1; // mark visited

    dfs(grid, r + 1, c, m, n);
    dfs(grid, r - 1, c, m, n);
    dfs(grid, r, c + 1, m, n);
    dfs(grid, r, c - 1, m, n);
}

int closedIsland(int** grid, int gridSize, int* gridColSize) {
    int m = gridSize;
    int n = gridColSize[0];
    int count = 0;

    // remove all land connected to border
    for (int i = 0; i < m; i++) {
        if (grid[i][0] == 0)
            dfs(grid, i, 0, m, n);
        if (grid[i][n - 1] == 0)
            dfs(grid, i, n - 1, m, n);
    }

    for (int j = 0; j < n; j++) {
        if (grid[0][j] == 0)
            dfs(grid, 0, j, m, n);
        if (grid[m - 1][j] == 0)
            dfs(grid, m - 1, j, m, n);
    }

    // remaining land must be closed islands
    for (int i = 1; i < m - 1; i++) {
        for (int j = 1; j < n - 1; j++) {
            if (grid[i][j] == 0) {
                count++;
                dfs(grid, i, j, m, n);
            }
        }
    }

    return count;
}
相关推荐
电科_银尘5 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴8 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David8 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
戊本菌9 小时前
进程(三)进程优先级:谁先上 CPU
linux·c语言·硬件架构
LK_0711 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi11 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK11 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
文丑颜不良啊12 小时前
LeetCode3341~3360题目解析
java·leetcode
上海潭龙东海科技有限公司13 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
嵌入式 Linux手记13 小时前
一块内存,三种解释:union 的真实用法
linux·c语言·驱动开发·嵌入式