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, grid[0].length <= 100
0 <= grid[i][j] <=1
class Solution { public int closedIsland(int[][] grid) { int m = grid.length; int n = grid[0].length; int res = 0; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(grid[i][j] == 0 && i == 0 || j == 0 || i == m - 1 || j == n - 1) help(i, j, grid); } } for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(grid[i][j] == 0){ res++; help(i, j, grid); } } } return res; } public void help(int r, int c, int[][] grid){ if(r > -1 && r < grid.length && c > -1 && c < grid[0].length && grid[r][c] == 0) grid[r][c] = 1; else return; help(r + 1, c, grid); help(r, c + 1, grid); help(r - 1, c, grid); help(r, c - 1, grid); } }
DFS, 先把边界的0区域全置1,然后再遍历,遇到0就先加1,然后再把该0区域置1,最后得到答案。
class Solution { public int closedIsland(int[][] grid) { int res = 0; for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[0].length; j++) { if(grid[i][j] == 0) { if(isvalid(grid, i, j)) res++; } } } return res; } public boolean isvalid(int[][] grid, int i, int j) { if(i < 0 || j < 0 || j >= grid[0].length || i >= grid.length) return false; if(grid[i][j] == 1) return true; grid[i][j] = 1; boolean flag = true; if(!isvalid(grid, i + 1, j)) flag = false; if(!isvalid(grid, i, j - 1)) flag = false; if(!isvalid(grid, i - 1, j)) flag = false; if(!isvalid(grid, i, j + 1)) flag = false; return flag; } }
如果要把所有周围的岛涂成1,一定要一个一个来,如果用&& ||,尤其是||,可能会出问题,因为有可能涂到一半就不涂了,四个方向one by one可以避免这个问题。
或者
class Solution { int[][] dir = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public int closedIsland(int[][] grid) { int res = 0; for(int i = 0; i < grid.length; i++){ for(int j = 0; j < grid[0].length; j++){ if(grid[i][j] == 0){ if(dfs(grid, i, j)) res++; } } } return res; } public boolean dfs(int[][] grid, int x, int y){ if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) return false; if(grid[x][y] == 1) return true; grid[x][y] = 1; return dfs(grid, x + 1, y) & dfs(grid, x, y + 1) & dfs(grid, x - 1, y) & dfs(grid, x, y - 1); } }