-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution2.ts
33 lines (33 loc) · 962 Bytes
/
Solution2.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function numEnclaves(grid: number[][]): number {
const [m, n] = [grid.length, grid[0].length];
const dirs = [-1, 0, 1, 0, -1];
const q: number[][] = [];
for (let j = 0; j < n; ++j) {
for (let i of [0, m - 1]) {
if (grid[i][j] === 1) {
q.push([i, j]);
grid[i][j] = 0;
}
}
}
for (let i = 0; i < m; ++i) {
for (let j of [0, n - 1]) {
if (grid[i][j] === 1) {
q.push([i, j]);
grid[i][j] = 0;
}
}
}
while (q.length) {
const [i, j] = q.pop()!;
for (let k = 0; k < 4; ++k) {
const x = i + dirs[k];
const y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] === 1) {
q.push([x, y]);
grid[x][y] = 0;
}
}
}
return grid.flat().reduce((acc, cur) => acc + cur, 0);
}