In a given 2D binary array grid, there are two islands. (An island is a 4-directionally connected group of 1s not connected to any other 1s.)
Now, we may change 0s to 1s so as to connect the two islands together to form 1 island.
Return the smallest number of 0s 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 or grid[i][j] == 1
其实在搭桥的过程中把0改2就是剪枝,理论上都不改成2结果也不会变,因为BFS是个不断扩大的过程,不剪支就是往外扩的同时也往过去经过的地方扩,只不过会变慢,因为重复查找了。
class Solution {
public:
vector<int> dir{-1,0,1,0,-1};
int shortestBridge(vector<vector<int>>& grid) {
int marked = 0;
queue<pair<int,int>> q;
//利用DFS将其中一个岛的所有1改成2以区分两岛,并把与其接壤的0都入队
for(int i = 0; i < grid.size(); i++){
if(marked)
break;
for(int j = 0; j < grid[0].size(); j++){
if(grid[i][j] == 1){
markisland(grid,q,i,j);
marked = 1;
break;
}
}
}
int step = 0;
while(!q.empty()){
step++;
int qsize = q.size();
while(qsize--){//每次把一层的全遍历一遍,以计算步数
auto [i,j] = q.front();
q.pop();
for(int k = 0; k < dir.size()-1; k++){
int x = i + dir[k];
int y = j + dir[k+1];
//把本层的0改成2以防把第一层当成再次第二层,把第二层0入队,碰到1就返回
if(x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size()){
if(grid[x][y] == 0){
grid[x][y] = 2;
q.push({x,y});
}
else if(grid[x][y] == 1)
return step;
}
}
}
}
return 0;
}
void markisland(vector<vector<int>>& grid, queue<pair<int,int>> &q, int i, int j){
grid[i][j] = 2;
for(int k = 0; k < dir.size()-1; k++){
int x = i + dir[k];
int y = j + dir[k+1];
if(x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size()){
if(grid[x][y] == 1)
markisland(grid,q,x,y);
else if(grid[x][y] == 0){
grid[x][y] = 2;
q.push({x,y});
}
}
}
}
};