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;
}
相关推荐
ZhengEnCi2 小时前
Agent 架构怎么选:从单 Agent 到多 Agent 编排的选型决策指南
算法·架构
秋天的怀念_David3 小时前
第二十二夜 · 数字迷雾
java·程序人生·算法
Pniubi3 小时前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
hhb_6184 小时前
大模型落地三重优化实战
人工智能·算法·机器学习
云和数据.ChenGuang4 小时前
光哥说Python RAG 系统需要哪些评估指标:从检索到生成的全链路评测指南
网络·人工智能·python·算法·langchain
2601_970703835 小时前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
心中有你02145 小时前
Java实现Dijkstra最短路径算法(邻接表 + 优先队列)
java·数据库·算法
ZhengEnCi6 小时前
同样的模型,为什么本地和云 API 差别那么大:量化精度、聊天模板与采样参数的三大元凶
人工智能·算法·llm
Zwawa6 小时前
串口为什么会丢字节:从轮询到中断和环形缓冲区
c语言·单片机·嵌入式
Flynn Liang7 小时前
RAG 答非所问/幻觉怎么破?Spring AI QuestionAnswerAdvisor 召回优化实战(TopK/重排/混合检索)
人工智能·算法·spring·rag·幻觉·springai