Skip to content

Commit fdd9620

Browse files
authored
Create 1254-number-of-closed-islands.js
1 parent f238078 commit fdd9620

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

1254-number-of-closed-islands.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @return {number}
4+
*/
5+
const closedIsland = function(grid) {
6+
const m = grid.length, n = grid[0].length
7+
const arr = []
8+
for(let i = 0; i < m; i++) {
9+
for(let j = 0; j < n; j++) {
10+
if(grid[i][j] === 0) arr.push([i, j])
11+
}
12+
}
13+
const dirs = [[0,1], [0,-1], [1,0], [-1,0]]
14+
let num = 2
15+
for(const [i, j] of arr) {
16+
if(grid[i][j] !== 0) continue
17+
else {
18+
bfs(i, j, num)
19+
num++
20+
}
21+
}
22+
23+
let res = 0
24+
const set = new Set()
25+
for(let i = 2; i < num; i++) {
26+
set.add(i)
27+
}
28+
29+
for(let i = 0; i < m; i++) {
30+
for(let j = 0; j < n; j++) {
31+
if(grid[i][j] > 1 && invalid(i, j)) {
32+
set.delete(grid[i][j])
33+
}
34+
}
35+
}
36+
return set.size
37+
38+
function invalid(i,j) {
39+
if(i === 0 || i === m - 1 || j === 0 || j === n - 1) return true
40+
return false
41+
}
42+
function bfs(i, j, v) {
43+
let q = [[i,j]]
44+
grid[i][j] = v
45+
while(q.length) {
46+
const tmp = []
47+
const size = q.length
48+
49+
for(const [x, y] of q) {
50+
for(const [dx, dy] of dirs) {
51+
const nx = x + dx, ny = y + dy
52+
if(nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] === 0) {
53+
grid[nx][ny] = v
54+
tmp.push([nx, ny])
55+
}
56+
}
57+
}
58+
59+
q = tmp
60+
}
61+
}
62+
};

0 commit comments

Comments
 (0)