-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0934-shortest-bridge.js
70 lines (55 loc) · 1.45 KB
/
0934-shortest-bridge.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const DIRECTIONS = [[-1, 0], [1, 0], [0, -1], [0, 1]];
const shortestBridge = (grid) => {
const rows = grid.length;
const cols = grid[0].length;
let queue = [];
const exploreIslandDFS = (row, col) => {
if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] !== 1) {
return false;
}
queue.push([row, col]);
grid[row][col] = 2;
exploreIslandDFS(row - 1, col);
exploreIslandDFS(row + 1, col);
exploreIslandDFS(row, col - 1);
exploreIslandDFS(row, col + 1);
return true;
};
const buildBridgeBFS = () => {
let distance = -1;
let currentQueue = [];
while (queue.length) {
currentQueue = queue;
queue = [];
for (let [row, col] of currentQueue) {
for (let [dx, dy] of DIRECTIONS) {
const nextRow = row + dx;
const nextCol = col + dy;
if (
nextRow >= 0 &&
nextRow < rows &&
nextCol >= 0 &&
nextCol < cols &&
grid[nextRow][nextCol] !== 2
) {
if (grid[nextRow][nextCol] === 1) {
return distance + 1;
}
queue.push([nextRow, nextCol]);
grid[nextRow][nextCol] = 2;
}
}
}
distance++;
}
return -1;
};
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (exploreIslandDFS(i, j)) {
return buildBridgeBFS();
}
}
}
return -1;
};