Number of Enclaves LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} grid
3
* @return {number}
4
*/
5
var numEnclaves = function (grid) {
6
let count = 0,
7
rowLength = grid.length,
8
colLength = grid[0].length;
9

10
const updateBoundaryLand = (row, col) => {
11
if (grid?.[row]?.[col]) {
12
grid[row][col] = 0;
13
updateBoundaryLand(row + 1, col);
14
updateBoundaryLand(row - 1, col);
15
updateBoundaryLand(row, col + 1);
16
updateBoundaryLand(row, col - 1);
17
}
18
};
19

20
for (let i = 0; i < rowLength; i++) {
21
if (grid[i][0] || grid[i][colLength - 1]) {
22
updateBoundaryLand(i, 0);
23
updateBoundaryLand(i, colLength - 1);
24
}
25
}
26

27
for (let j = 0; j < colLength; j++) {
28
if (grid[0][j] || grid[rowLength - 1][j]) {
29
updateBoundaryLand(0, j);
30
updateBoundaryLand(rowLength - 1, j);
31
}
32
}
33

34
for (let i = 0; i < rowLength; i++) {
35
for (let j = 0; j < colLength; j++) {
36
if (grid[i][j]) count++;
37
}
38
}
39

40
return count;
41
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0