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
1 class Solution { 2 public int closedIsland(int[][] grid) { 3 if (grid == null || grid.length == 0) return 0; 4 int rows = grid.length; 5 int cols = grid[0].length; 6 for (int i = 0; i < rows; i++) { 7 for (int j = 0; j < cols; j++) { 8 if ((i == 0 || j == 0 || i == rows - 1 || j == cols - 1) && grid[i][j] == 0) { 9 dfs(grid, i, j); 10 } 11 } 12 } 13 int count = 0; 14 for (int i = 1; i < rows - 1; i++) { 15 for (int j = 1; j < cols - 1; j++) { 16 if (grid[i][j] == 0) { 17 dfs(grid, i, j); 18 count++; 19 } 20 } 21 } 22 return count; 23 } 24 25 private void dfs(int[][] grid, int i, int j) { 26 int rows = grid.length; 27 int cols = grid[0].length; 28 if (i < 0 || i >= rows || j < 0 || j >= cols || grid[i][j] != 0) return; 29 30 grid[i][j] = 1; 31 dfs(grid, i - 1, j); 32 dfs(grid, i + 1, j); 33 dfs(grid, i, j + 1); 34 dfs(grid, i, j - 1); 35 } 36 }