|
| 1 | +/** |
| 2 | + * 1020. Number of Enclaves |
| 3 | + * https://leetcode.com/problems/number-of-enclaves/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents |
| 7 | + * a land cell. |
| 8 | + * |
| 9 | + * A move consists of walking from one land cell to another adjacent (4-directionally) land cell |
| 10 | + * or walking off the boundary of the grid. |
| 11 | + * |
| 12 | + * Return the number of land cells in grid for which we cannot walk off the boundary of the grid |
| 13 | + * in any number of moves. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number[][]} grid |
| 18 | + * @return {number} |
| 19 | + */ |
| 20 | +var numEnclaves = function(grid) { |
| 21 | + const rows = grid.length; |
| 22 | + const cols = grid[0].length; |
| 23 | + |
| 24 | + for (let i = 0; i < rows; i++) { |
| 25 | + exploreBoundary(i, 0); |
| 26 | + exploreBoundary(i, cols - 1); |
| 27 | + } |
| 28 | + |
| 29 | + for (let j = 0; j < cols; j++) { |
| 30 | + exploreBoundary(0, j); |
| 31 | + exploreBoundary(rows - 1, j); |
| 32 | + } |
| 33 | + |
| 34 | + let result = 0; |
| 35 | + for (let i = 0; i < rows; i++) { |
| 36 | + for (let j = 0; j < cols; j++) { |
| 37 | + result += grid[i][j]; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return result; |
| 42 | + |
| 43 | + function exploreBoundary(row, col) { |
| 44 | + if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] !== 1) return; |
| 45 | + grid[row][col] = 0; |
| 46 | + exploreBoundary(row + 1, col); |
| 47 | + exploreBoundary(row - 1, col); |
| 48 | + exploreBoundary(row, col + 1); |
| 49 | + exploreBoundary(row, col - 1); |
| 50 | + } |
| 51 | +}; |
0 commit comments