-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0934-shortest-bridge.js
More file actions
88 lines (78 loc) · 2.18 KB
/
0934-shortest-bridge.js
File metadata and controls
88 lines (78 loc) · 2.18 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* Shortest Bridge
* Time Complexity: O(N*N)
* Space Complexity: O(N*N)
*/
var shortestBridge = function (grid) {
const matrixDimension = grid.length;
const expansionQueue = [];
const moveOffsets = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
];
const exploreIsland = (depthFirstRow, depthFirstCol) => {
if (
depthFirstRow < 0 ||
depthFirstRow >= matrixDimension ||
depthFirstCol < 0 ||
depthFirstCol >= matrixDimension ||
grid[depthFirstRow][depthFirstCol] !== 1
) {
return;
}
grid[depthFirstRow][depthFirstCol] = 2;
expansionQueue.push([depthFirstRow, depthFirstCol]);
for (const [deltaRowDfs, deltaColDfs] of moveOffsets) {
exploreIsland(depthFirstRow + deltaRowDfs, depthFirstCol + deltaColDfs);
}
};
let firstIslandFoundFlag = false;
outerIslandSearch: for (
let rowIterator = 0;
rowIterator < matrixDimension;
rowIterator++
) {
for (let colIterator = 0; colIterator < matrixDimension; colIterator++) {
if (grid[rowIterator][colIterator] === 1) {
exploreIsland(rowIterator, colIterator);
firstIslandFoundFlag = true;
break outerIslandSearch;
}
}
}
let currentBridgeLength = 0;
while (expansionQueue.length > 0) {
const currentLevelSize = expansionQueue.length;
for (
let levelIterator = 0;
levelIterator < currentLevelSize;
levelIterator++
) {
const dequeuedPosition = expansionQueue.shift();
const currentRow = dequeuedPosition[0];
const currentCol = dequeuedPosition[1];
for (const [deltaRow, deltaCol] of moveOffsets) {
const nextRow = currentRow + deltaRow;
const nextCol = currentCol + deltaCol;
if (
nextRow < 0 ||
nextRow >= matrixDimension ||
nextCol < 0 ||
nextCol >= matrixDimension ||
grid[nextRow][nextCol] === 2
) {
continue;
}
if (grid[nextRow][nextCol] === 1) {
return currentBridgeLength;
}
grid[nextRow][nextCol] = 2;
expansionQueue.push([nextRow, nextCol]);
}
}
currentBridgeLength++;
}
return currentBridgeLength;
};