Skip to content

Commit 69f16be

Browse files
authored
Update 934-shortest-bridge.js
1 parent 5f7de80 commit 69f16be

File tree

1 file changed

+46
-58
lines changed

1 file changed

+46
-58
lines changed

934-shortest-bridge.js

+46-58
Original file line numberDiff line numberDiff line change
@@ -3,65 +3,53 @@
33
* @return {number}
44
*/
55
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
6+
let r = A.length;
7+
let c = A[0].length;
8+
let found = false;
9+
let queue = [];
10+
for (let i = 0; i < r; i++) {
11+
for (let j = 0; j < c; j++) {
12+
if (A[i][j]) {
13+
dfs(A, i, j, queue);
14+
found = true;
15+
break;
16+
}
1617
}
17-
}
18+
if (found) break;
1819
}
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-
})
20+
21+
let replace = [];
22+
let count = 0;
23+
let cells = [[1, 0], [-1, 0], [0, 1], [0, -1]];
24+
while (queue.length) {
25+
let pos = queue.shift();
26+
27+
for (let i = 0; i < cells.length; i++) {
28+
let x = pos[0] + cells[i][0];
29+
let y = pos[1] + cells[i][1];
30+
31+
if (0 <= x && x < r && 0 <= y && y < c && A[x][y] != 2) {
32+
if (A[x][y] == 1) return count;
33+
A[x][y] = 2;
34+
replace.push([x, y]);
35+
}
36+
}
37+
38+
if (!queue.length) {
39+
queue = replace;
40+
replace = [];
41+
count++;
4442
}
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)
6643
}
67-
};
44+
};
45+
46+
function dfs(A, x, y, queue) {
47+
if (x < 0 || x >= A.length || y < 0 || y >= A[0].length || A[x][y] == 0 || A[x][y] == 2) return;
48+
49+
A[x][y] = 2;
50+
queue.push([x, y]);
51+
dfs(A, x-1, y, queue);
52+
dfs(A, x+1, y, queue);
53+
dfs(A, x, y-1, queue);
54+
dfs(A, x, y+1, queue);
55+
}

0 commit comments

Comments
 (0)