Skip to content

Commit 9042bf7

Browse files
authored
Create 1568-minimum-number-of-days-to-disconnect-island.js
1 parent 0d85c0b commit 9042bf7

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @return {number}
4+
*/
5+
const minDays = function (grid) {
6+
if (!grid.length || !grid[0].length) return 0
7+
if (numIslands(grid) != 1) return 0
8+
for (let i = 0; i < grid.length; i++) {
9+
for (let j = 0; j < grid[0].length; j++) {
10+
if (grid[i][j] == 1) {
11+
grid[i][j] = 0
12+
if (numIslands(grid) != 1) return 1
13+
grid[i][j] = 1
14+
}
15+
}
16+
}
17+
return 2
18+
}
19+
20+
function numIslands(grid) {
21+
let m = Array.from({ length: grid.length }, (v, i) => {
22+
return [...grid[i]]
23+
})
24+
let count = 0
25+
for (let i = 0; i < m.length; i++)
26+
for (let j = 0; j < m[0].length; j++) removeIslandAt(i, j, 1)
27+
return count
28+
function removeIslandAt(i, j, firstIteration = 0) {
29+
if (i >= m.length || j >= m[0].length || i < 0 || j < 0 || m[i][j] == 0)
30+
return
31+
m[i][j] = 0
32+
count += firstIteration
33+
removeIslandAt(i - 1, j)
34+
removeIslandAt(i + 1, j)
35+
removeIslandAt(i, j - 1)
36+
removeIslandAt(i, j + 1)
37+
}
38+
}

0 commit comments

Comments
 (0)