Skip to content

Commit 649c688

Browse files
authored
Create 1031-number-of-enclaves.js
1 parent 71dfab2 commit 649c688

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

1031-number-of-enclaves.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* @param {number[][]} A
3+
* @return {number}
4+
*/
5+
const numEnclaves = function(A) {
6+
let res = 0
7+
const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]
8+
const visited = Array.from({ length: A.length }, () =>
9+
new Array(A[0].length).fill(false)
10+
)
11+
for (let row = 0; row < A.length; row++) {
12+
for (let col = 0; A[0] && col < A[0].length; col++) {
13+
if (
14+
(row === 0 ||
15+
col === 0 ||
16+
row === A.length - 1 ||
17+
col === A[0].length - 1) &&
18+
A[row][col] === 1
19+
) {
20+
dfs(A, row, col, visited, dirs)
21+
}
22+
}
23+
}
24+
for (let row = 0; row < A.length; row++) {
25+
for (let col = 0; A[0] && col < A[0].length; col++) {
26+
if (A[row][col] === 1) {
27+
res += 1
28+
}
29+
}
30+
}
31+
return res
32+
}
33+
34+
function dfs(A, row, col, v, dirs) {
35+
if (
36+
row < 0 ||
37+
row >= A.length ||
38+
col < 0 ||
39+
col >= A[0].length ||
40+
v[row][col] ||
41+
A[row][col] === 0
42+
)
43+
return
44+
45+
v[row][col] = true
46+
A[row][col] = 0
47+
48+
for (let dir of dirs) {
49+
dfs(A, row + dir[0], col + dir[1], v, dirs)
50+
}
51+
}

0 commit comments

Comments
 (0)