题目描述:
In a given 2D binary array A
, 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: [[0,1],[1,0]] Output: 1
Example 2:
Input: [[0,1,0],[0,0,0],[0,0,1]] Output: 2
Example 3:
Input: [[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
Note:
1 <= A.length = A[0].length <= 100
A[i][j] == 0
orA[i][j] == 1
class Solution {
public:
int shortestBridge(vector<vector<int>>& A) {
// 利用DFS将一个岛的所有点都加入队列中,这些点的起始距离都是零
int m=A.size(), n=A[0].size();
queue<pair<int,int>> q;
unordered_map<int,int> dist;
bool found=false; // 必须加上一个变量表示有没有找到一个岛
for(int i=0;i<m&&!found;i++)
{
for(int j=0;j<n&&!found;j++)
{
if(A[i][j]==1)
{
DFS(A,i,j,q,dist);
found=true;
}
}
}
// 做BFS找最先遇到的另一个岛的点
vector<pair<int,int>> dirs={{0,1},{0,-1},{1,0},{-1,0}};
while(!q.empty())
{
int i=q.front().first, j=q.front().second;
q.pop();
for(pair<int,int> dir:dirs)
{
int x=i+dir.first, y=j+dir.second;
if(x<0||x>=m||y<0||y>=n||dist.count(x*n+y)) continue;
dist[x*n+y]=dist[i*n+j]+1;
if(A[x][y]==1) return dist[x*n+y]-1; // 需要修改的节点数是距离减一
q.push({x,y});
}
}
return -1;
}
void DFS(vector<vector<int>>& A, int i, int j, queue<pair<int,int>>& q, unordered_map<int,int>& dist)
{
int m=A.size(), n=A[0].size();
if(A[i][j]!=1||dist.count(i*n+j)) return;
dist[i*n+j]=0;
q.push({i,j});
if(i>0) DFS(A,i-1,j,q,dist);
if(i<n-1) DFS(A,i+1,j,q,dist);
if(j>0) DFS(A,i,j-1,q,dist);
if(j<m-1) DFS(A,i,j+1,q,dist);
}
};