In a given 2D binary array grid
, there are two islands. (An island is a 4-directionally connected group of 1
s not connected to any other 1s.)
Now, we may change 0
s to 1
s so as to connect the two islands together to form 1 island.
Return the smallest number of 0
s that must be flipped. (It is guaranteed that the answer is at least 1.)
Example 1:
Input: grid = [[0,1],[1,0]] Output: 1
Example 2:
Input: grid = [[0,1,0],[0,0,0],[0,0,1]] Output: 2
Example 3:
Input: grid = [[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]] Output: 1
Constraints:
2 <= grid.length == grid[0].length <= 100
grid[i][j] == 0
orgrid[i][j] == 1
Companies:
Microsoft, Google, Uber, Bloomberg, Snapchat
Related Topics:
Depth-first Search, Breadth-first Search
// OJ: https://leetcode.com/problems/shortest-bridge/
// Author: github.com/lzl124631x
// Time: O(MN)
// Space: O(MN)
class Solution {
int M, N, dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
queue<pair<int, int>> qa, qb;
void dfs(vector<vector<int>> &A, int x, int y, int color) {
A[x][y] = color;
if (color == 2) qa.emplace(x, y);
else qb.emplace(x, y);
for (auto &[dx, dy] : dirs) {
int a = x + dx, b = y + dy;
if (a < 0 || b < 0 || a >= M || b >= N || A[a][b] != 1) continue;
dfs(A, a, b, color);
}
}
void bfs(vector<vector<int>> &A, queue<pair<int, int>> &q, vector<vector<int>> &dist) {
int step = 1;
while (q.size()) {
int cnt = q.size();
while (cnt--) {
auto [x, y] = q.front();
q.pop();
for (auto &[dx, dy] : dirs) {
int a = x + dx, b = y + dy;
if (a < 0 || b < 0 || a >= M || b >= N || A[a][b] != 0 || dist[a][b] != INT_MAX) continue;
dist[a][b] = step;
q.emplace(a, b);
}
}
++step;
}
}
public:
int shortestBridge(vector<vector<int>>& A) {
M = A.size(), N = A[0].size();
int color = 2, ans = INT_MAX;
vector<vector<int>> da(M, vector<int>(N, INT_MAX)), db(M, vector<int>(N, INT_MAX));
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (A[i][j] == 1) dfs(A, i, j, color++);
}
}
bfs(A, qa, da);
bfs(A, qb, db);
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (A[i][j] == 0 && da[i][j] != INT_MAX && db[i][j] != INT_MAX) ans = min(ans, da[i][j] + db[i][j] - 1);
}
}
return ans;
}
};