[Med] LeetCode 1254. Number of Closed Islands
链接: https://leetcode.com/problems/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.
有一个二维矩阵 grid ,每个位置要么是陆地(记号为 0 )要么是水域(记号为 1 )。
我们从一块陆地出发,每次可以往上下左右 4 个方向相邻区域走,能走到的所有陆地区域,我们将其称为一座「岛屿」。
如果一座岛屿 完全 由水域包围,即陆地边缘上下左右所有相邻区域都是水域,那么我们将其称为 「封闭岛屿」。
请返回封闭岛屿的数目。
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
Note:
- 1 <= grid.length, grid[0].length <= 100
- 0 <= grid[i][j] <=1
Tag: Matrix
解题思路
这道题目和200.number of islands有点像,在那道题目里面让我们找到所有由1组成的岛屿的个数。在这里稍微有一点变换,这道题让我们找到由0构成的岛屿,但是岛屿周围必须要被1包围着才能算入最后结果中。比如说例子1当中,最右边的(0,7)这个点往下的岛屿就不算数,因为并没有完全被1所包括。其实这道题目还是比较简单的,我们换一个思路,就是只要和边界相接的岛屿就不算入最后的结果当中就好了。如果遇到超过边界的情况,我们就返回false,原因之所以越过边界是因为边界位置是岛屿才可能越过去。如果遇到某一个位置是1那么我们直接返回true就好。
我们最后检查岛屿是否有触及边界,如果做BFS之后没有触碰边界的情况,那么这个岛屿就计入最后结果当中。
解法一:
class Solution {
public int closedIsland(int[][] grid) {
int enclosed = 0;
for(int i=0; i < grid.length; i++){
for(int j=0; j<grid[0].length; j++){
if(grid[i][j] == 0){
if(checkEnclosed(grid, i, j)) enclosed++;
}
}
}
return enclosed;
}
public boolean checkEnclosed(int[][] grid, int i, int j){
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return false;
if(grid[i][j] == 1) return true;
grid[i][j] = 1;
boolean down = checkEnclosed(grid, i+1, j);
boolean up = checkEnclosed(grid, i-1, j);
boolean right = checkEnclosed(grid, i, j+1);
boolean left = checkEnclosed(grid, i, j-1);
return up && down && left && right;
}
}