|
| 1 | +/** |
| 2 | + * 1254. Number of Closed Islands |
| 3 | + * https://leetcode.com/problems/number-of-closed-islands/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally |
| 7 | + * connected group of 0s and a closed island is an island totally (all left, top, right, bottom) |
| 8 | + * surrounded by 1s. |
| 9 | + * |
| 10 | + * Return the number of closed islands. |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * @param {number[][]} grid |
| 15 | + * @return {number} |
| 16 | + */ |
| 17 | +var closedIsland = function(grid) { |
| 18 | + const rows = grid.length; |
| 19 | + const cols = grid[0].length; |
| 20 | + |
| 21 | + for (let i = 0; i < rows; i++) { |
| 22 | + markBorderConnected(i, 0); |
| 23 | + markBorderConnected(i, cols - 1); |
| 24 | + } |
| 25 | + for (let j = 0; j < cols; j++) { |
| 26 | + markBorderConnected(0, j); |
| 27 | + markBorderConnected(rows - 1, j); |
| 28 | + } |
| 29 | + |
| 30 | + let result = 0; |
| 31 | + for (let i = 1; i < rows - 1; i++) { |
| 32 | + for (let j = 1; j < cols - 1; j++) { |
| 33 | + result += countClosed(i, j); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return result; |
| 38 | + |
| 39 | + function markBorderConnected(row, col) { |
| 40 | + if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] !== 0) return; |
| 41 | + grid[row][col] = 1; |
| 42 | + markBorderConnected(row - 1, col); |
| 43 | + markBorderConnected(row + 1, col); |
| 44 | + markBorderConnected(row, col - 1); |
| 45 | + markBorderConnected(row, col + 1); |
| 46 | + } |
| 47 | + |
| 48 | + function countClosed(row, col) { |
| 49 | + if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] !== 0) return 0; |
| 50 | + grid[row][col] = 1; |
| 51 | + countClosed(row - 1, col); |
| 52 | + countClosed(row + 1, col); |
| 53 | + countClosed(row, col - 1); |
| 54 | + countClosed(row, col + 1); |
| 55 | + return 1; |
| 56 | + } |
| 57 | +}; |
0 commit comments