Description
Number of Closed Islands
MediumGiven 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 <= 1000 <= grid[i][j] <=1
Solutions
Fun exploration algorithm, interesting to see evolution from today's code to 4-years-old code.
Language: javascript()DONE
CPU Performance54.25%
x
Memory Performance82.37%
x
/**
* @param {number[][]} grid
* @return {number}
*/
var closedIsland = function(grid) {
const rows = grid.length;
const cols = grid[0].length;
const explore = (id, row, col) => {
if (row < 0 || row >= rows || col < 0 || col >= cols) return false;
if (grid[row][col] === 1 || grid[row][col] === id) return true;
if (grid[row][col] !== 0) return false;
grid[row][col] = id;
const temp = explore(id, row, col + 1) &&
explore(id, row + 1, col) &&
explore(id, row, col - 1) &&
explore(id, row - 1, col);
if (!temp) {
grid[row][col] = -1;
}
return temp;
};
let res = 0;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
if (grid[row][col] === 0) {
if (explore(res + 2, row, col)) {
res++;
}
}
}
}
return res;
};