Shortest Bridge

Find one island via DFS, then multi-source BFS outward from it; first time we hit the second island is the answer.

Medium
Time O(n^2) Space O(n^2)
LeetCode
7 min read
bfs dfs matrix graph

Problem#

In a binary grid with exactly two islands of 1s, return the minimum number of 0s to flip so the two islands connect.

Examples#

  • [[0,1],[1,0]]1.
  • [[0,1,0],[0,0,0],[0,0,1]]2; [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]1.

Constraints#

  • 2 <= n <= 100.

Approach#

DFS-flood the first island, pushing all its cells into a BFS queue and marking them as visited. BFS outward by levels through 0s; the first time we touch a 1 (the second island), the current level minus 1 is the answer.

Solution#

Shortest Bridge
class Solution {
int m, n;
int dr[4] = {-1, 1, 0, 0}, dc[4] = {0, 0, -1, 1};
public:
int shortestBridge(vector<vector<int>>& g) {
m = g.size(); n = g[0].size();
queue<pair<int,int>> q;
function<void(int,int)> dfs = [&](int r, int c) {
if (r < 0 || r >= m || c < 0 || c >= n || g[r][c] != 1) return;
g[r][c] = 2;
q.push({r, c});
for (int k = 0; k < 4; ++k) dfs(r + dr[k], c + dc[k]);
};
bool found = false;
for (int i = 0; i < m && !found; ++i)
for (int j = 0; j < n && !found; ++j)
if (g[i][j] == 1) { dfs(i, j); found = true; }
int steps = 0;
while (!q.empty()) {
int sz = q.size();
while (sz--) {
auto [r, c] = q.front(); q.pop();
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
if (g[nr][nc] == 2) continue;
if (g[nr][nc] == 1) return steps;
g[nr][nc] = 2;
q.push({nr, nc});
}
}
++steps;
}
return -1;
}
};

Editorial#

The two-phase trick — flood one island, then BFS the gap — is the standard “shortest path between two regions” recipe. Multi-source BFS from the first island ensures the very first frontier intersection with the second island is the minimum bridge.

Complexity#

  • Time: O(n^2).
  • Space: O(n^2).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.