leetcode-1254
/**
<p>二维矩阵 <code>grid</code> 由 <code>0</code> (土地)和 <code>1</code> (水)组成。岛是由最大的4个方向连通的 <code>0</code> 组成的群,封闭岛是一个 <code>完全</code> 由1包围(左、上、右、下)的岛。</p>
<p>请返回 <em>封闭岛屿</em> 的数目。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode.com/uploads/2019/10/31/sample_3_1610.png" style="height: 151px; width: 240px;" /></p>
<pre>
<strong>输入:</strong>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]]
<strong>输出:</strong>2
<strong>解释:</strong>
灰色区域的岛屿是封闭岛屿,因为这座岛屿完全被水域包围(即被 1 区域包围)。</pre>
<p><strong>示例 2:</strong></p>
<p><img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/11/07/sample_4_1610.png" style="height: 98px; width: 160px;" /></p>
<pre>
<strong>输入:</strong>grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
<strong>输出:</strong>1
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>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]]
<strong>输出:</strong>2
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= grid.length, grid[0].length <= 100</code></li>
<li><code>0 <= grid[i][j] <=1</code></li>
</ul>
<div><div>Related Topics</div><div><li>深度优先搜索</li><li>广度优先搜索</li><li>并查集</li><li>数组</li><li>矩阵</li></div></div><br><div><li>👍 144</li><li>👎 0</li></div>
*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int closedIsland(int[][] grid) {
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 j = 0; j < n; j++) {
dfs(grid,0,j);
dfs(grid,m-1,j);
}
int res = 0;
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;
}
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, j + 1);
dfs(grid, i - 1, j);
dfs(grid, i, j - 1);
}
}
//leetcode submit region end(Prohibit modification and deletion)
不恋尘世浮华,不写红尘纷扰