1.题目
二维矩阵 grid 由 0 (土地)和 1(水)组成。岛是由最大的4个方向连通的 0 组成的群,封闭岛是一个完全由1包围(左、上、右、下)的岛。
请返回封闭岛屿的数目。
示例 1: 输入: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]] 输出:2 解释: 灰色区域的岛屿是封闭岛屿,因为这座岛屿完全被水域包围(即被 1 区域包围)。
示例 2: 输入:grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]] 输出:1
示例 3:
输入: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]]
输出:2
提示: 1 <= grid.length, grid[0].length <= 100 0 <= grid[i][j] <=1
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/number-of-closed-islands
2.思路
(1)DFS 本题其实是LeetCode_DFS_中等_200.岛屿数量这题的变形,只需在其基础上去掉 grid 中四周不封闭的岛屿即可。
3.代码实现(Java)
class Solution {
public int closedIsland(int[][] grid) {
int res = 0;
int m = grid.length;
int n = grid[0].length;
for (int i = 0; i < m; i++) {
dfs(grid, i, 0);
dfs(grid, i, n - 1);
}
for (int i = 0; i < n; i++) {
dfs(grid, 0, i);
dfs(grid, m - 1, i);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 0) {
res++;
dfs(grid, i, j);
}
}
}
return res;
}
public void dfs(int[][] grid, int i, int j) {
int m = grid.length;
int n = grid[0].length;
if (i < 0 || j < 0 || i >= m || j >= n) {
return;
}
if (grid[i][j] == 1) {
return;
}
grid[i][j] = 1;
dfs(grid, i - 1, j);
dfs(grid, i + 1, j);
dfs(grid, i, j - 1);
dfs(grid, i, j + 1);
}
}
|