Skip to content

Commit efad2c0

Browse files
committed
Add solution #934
1 parent 686e17b commit efad2c0

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -743,6 +743,7 @@
743743
931|[Minimum Falling Path Sum](./solutions/0931-minimum-falling-path-sum.js)|Medium|
744744
932|[Beautiful Array](./solutions/0932-beautiful-array.js)|Medium|
745745
933|[Number of Recent Calls](./solutions/0933-number-of-recent-calls.js)|Easy|
746+
934|[Shortest Bridge](./solutions/0934-shortest-bridge.js)|Medium|
746747
937|[Reorder Data in Log Files](./solutions/0937-reorder-data-in-log-files.js)|Medium|
747748
966|[Vowel Spellchecker](./solutions/0966-vowel-spellchecker.js)|Medium|
748749
970|[Powerful Integers](./solutions/0970-powerful-integers.js)|Easy|

Diff for: solutions/0934-shortest-bridge.js

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* 934. Shortest Bridge
3+
* https://leetcode.com/problems/shortest-bridge/
4+
* Difficulty: Medium
5+
*
6+
* You are given an n x n binary matrix grid where 1 represents land and 0 represents water.
7+
*
8+
* An island is a 4-directionally connected group of 1's not connected to any other 1's.
9+
* There are exactly two islands in grid.
10+
*
11+
* You may change 0's to 1's to connect the two islands to form one island.
12+
*
13+
* Return the smallest number of 0's you must flip to connect the two islands.
14+
*/
15+
16+
/**
17+
* @param {number[][]} grid
18+
* @return {number}
19+
*/
20+
var shortestBridge = function(grid) {
21+
const n = grid.length;
22+
const queue = [];
23+
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
24+
25+
outer: for (let i = 0; i < n; i++) {
26+
for (let j = 0; j < n; j++) {
27+
if (grid[i][j] === 1) {
28+
findFirstIsland(i, j);
29+
break outer;
30+
}
31+
}
32+
}
33+
34+
let distance = 0;
35+
while (queue.length) {
36+
const size = queue.length;
37+
for (let i = 0; i < size; i++) {
38+
const [row, col] = queue.shift();
39+
for (const [dx, dy] of directions) {
40+
const newRow = row + dx;
41+
const newCol = col + dy;
42+
if (newRow < 0 || newRow >= n || newCol < 0 || newCol >= n
43+
|| grid[newRow][newCol] === 2) continue;
44+
if (grid[newRow][newCol] === 1) return distance;
45+
grid[newRow][newCol] = 2;
46+
queue.push([newRow, newCol]);
47+
}
48+
}
49+
distance++;
50+
}
51+
52+
return distance;
53+
54+
function findFirstIsland(row, col) {
55+
if (row < 0 || row >= n || col < 0 || col >= n || grid[row][col] !== 1) return;
56+
grid[row][col] = 2;
57+
queue.push([row, col]);
58+
for (const [dx, dy] of directions) {
59+
findFirstIsland(row + dx, col + dy);
60+
}
61+
}
62+
};

0 commit comments

Comments
 (0)