Minimum Number of Days to Disconnect Island LeetCode solution in JavaScript

1
let directions = [
2
[-1, 0],
3
[1, 0],
4
[0, -1],
5
[0, 1],
6
];
7

8
var minDays = function (grid) {
9
let colorNumber = 2;
10
let landCells = [];
11

12
function colorIsland(i, j) {
13
grid[i][j] = colorNumber;
14
for (let k = 0; k < directions.length; k++) {
15
let newI = i + directions[k][0];
16
let newJ = j + directions[k][1];
17

18
if (
19
newI >= 0 &&
20
newJ >= 0 &&
21
newI < grid.length &&
22
newJ < grid[0].length &&
23
grid[newI][newJ] &&
24
grid[newI][newJ] != colorNumber
25
) {
26
colorIsland(newI, newJ);
27
}
28
}
29
}
30

31
function addLandCells() {
32
for (let i = 0; i < grid.length; i++) {
33
for (let j = 0; j < grid[0].length; j++) {
34
if (grid[i][j]) {
35
landCells.push([i, j]);
36
}
37
}
38
}
39
}
40

41
function findAnotherIsland() {
42
for (let i = 0; i < grid.length; i++) {
43
for (let j = 0; j < grid[0].length; j++) {
44
if (grid[i][j] && grid[i][j] != colorNumber) {
45
return true;
46
}
47
}
48
}
49
return false;
50
}
51

52
addLandCells();
53

54
if (landCells.length < 2) {
55
return landCells.length;
56
}
57

58
colorIsland(landCells[0][0], landCells[0][1]);
59

60
if (findAnotherIsland()) {
61
return 0;
62
}
63

64
colorNumber++;
65

66
for (let i = 0; i < landCells.length; i++) {
67
grid[landCells[i][0]][landCells[i][1]] = 0;
68
colorIsland(
69
landCells[(i + 1) % landCells.length][0],
70
landCells[(i + 1) % landCells.length][1]
71
);
72
if (findAnotherIsland()) {
73
return 1;
74
}
75
grid[landCells[i][0]][landCells[i][1]] = colorNumber;
76
colorNumber++;
77
}
78

79
return 2;
80
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0