示例代码
class Solution {
public:
queue<pair<int,int>> points;
vector<int> direc={-1,0,1,0,-1};
int m,n;
void dfs(vector<vector<int>>& grid,int r,int c){
if(grid[r][c]==0){
points.push({r,c});
return;
}
grid[r][c]=2;
for(int i=0;i<4;i++){
int x=r+direc[i],y=c+direc[i+1];
if(x>=0&&x<m&&y>=0&&y<n&&grid[x][y]!=2){
dfs(grid,x,y);
}
}
}
int shortestBridge(vector<vector<int>>& grid) {
m=grid.size(),n=grid[0].size();
//dfs寻找第一个岛屿,并把1全部赋值为22
bool flag=false;
for(int i=0;i<m;i++){
if(flag){
break;
}
for(int j=0;j<n;j++){
if(grid[i][j]==1){
dfs(grid,i,j);
flag=true;
break;
}
}
}
//bfs寻找第二个岛屿,并把经过的0赋值为2
int level=0;
while(!points.empty()){
level++;
int len=points.size();
while(len--){
auto [r,c]=points.front();
points.pop();
for(int i=0;i<4;i++){
int x=r+direc[i],y=c+direc[i+1];
if(x>=0&&x<m&&y>=0&&y<n&&grid[x][y]!=2){
if(grid[x][y]==1){
return level;
}else{
points.push({x,y});
grid[x][y]=2;
}
}
}
}
}
return 0;
}
};
效果展示