二维矩阵 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
class Solution {
/**
注意当我们判断当前不是封闭岛时,不能直接return,还需要把所有岛屿置为1
*/
int[][] grid;
int n, m;
int[] dirs = new int[]{-1, 0, 1, 0, -1};
public int closedIsland(int[][] grid) {
this.grid = grid;
n = grid.length; m = grid[0].length;
int res = 0;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j) {
if (grid[i][j] == 0 && dfs(i, j))
res ++;
}
return res;
}
boolean dfs(int x, int y) {
if ((x == 0 || x == n - 1 || y == 0 || y == m - 1) && grid[x][y] == 0) return false;
boolean res = true;
//置为1
grid[x][y] = 1;
for (int i = 0; i < 4; ++i) {
int a = x + dirs[i], b = y + dirs[i + 1];
if (a < 0 || a >= n || b < 0 || b >= m || grid[a][b] == 1) continue;
res = res & dfs(a, b);
}
return res;
}
}