Skip to content

Commit 5f7de80

Browse files
authored
Create 934-shortest-bridge.js
1 parent dc8bf6d commit 5f7de80

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

934-shortest-bridge.js

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* @param {number[][]} A
3+
* @return {number}
4+
*/
5+
const shortestBridge = function(A) {
6+
const h = A.length
7+
const w = A[0].length
8+
let queue = []
9+
10+
let foundOneIsland = false
11+
for (let i = 0; i < h && !foundOneIsland; i++) {
12+
for (let j = 0; j < w && !foundOneIsland; j++) {
13+
if (A[i][j] == 1) {
14+
dfs(A, i, j, w, h)
15+
foundOneIsland = true
16+
}
17+
}
18+
}
19+
// BFS每一个元素向外扩展,直至找到另一个小岛
20+
const direction = [0, 1, 0, -1, 0]
21+
let result = 0
22+
while (queue.length !== 0) {
23+
let size = queue.length
24+
while (size--) {
25+
const item = queue.pop()
26+
const x = item.i
27+
const y = item.j
28+
for (let i = 0; i < 4; i++) {
29+
// 向四个方向扩展 技巧
30+
const newX = x + direction[i]
31+
const newY = y + direction[i + 1]
32+
if (newX < 0 || newY < 0 || newX > h - 1 || newY > w - 1 || A[newX][newY] == 2) {
33+
continue
34+
}
35+
// 找到另一个小岛
36+
if (A[newX][newY] == 1) {
37+
return result
38+
}
39+
A[newX][newY] = 2
40+
queue.unshift({
41+
i: newX,
42+
j: newY
43+
})
44+
}
45+
}
46+
++result
47+
}
48+
49+
return result
50+
51+
// 通过DFS找到其中一个小岛
52+
function dfs (A, i, j, w, h) {
53+
if (i < 0 || j < 0 || i > h - 1 || j > w - 1 || A[i][j] != '1') {
54+
return
55+
}
56+
57+
A[i][j] = 2
58+
queue.push({
59+
i,
60+
j
61+
})
62+
dfs(A, i - 1, j, w, h)
63+
dfs(A, i + 1, j, w, h)
64+
dfs(A, i, j - 1, w, h)
65+
dfs(A, i, j + 1, w, h)
66+
}
67+
};

0 commit comments

Comments
 (0)