题目描述:
在给定的二维二进制数组 A
中,存在两座岛。(岛是由四面相连的 1
形成的一个最大组。)
现在,我们可以将 0
变为 1
,以使两座岛连接起来,变成一座岛。
返回必须翻转的 0
的最小数目。(可以保证答案至少是 1。)
示例 1:
输入:[[0,1],[1,0]]
输出:1
示例 2:
输入:[[0,1,0],[0,0,0],[0,0,1]]
输出:2
示例 3:
输入:[[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
提示:
1 <= A.length = A[0].length <= 100
A[i][j] == 0
或A[i][j] == 1
解题思路:
先使用dfs将两块岛屿进行标记,区分成岛屿1与岛屿2,再使用bfs来寻找最近的连接距离
代码:
class Solution {
public:
int shortestBridge(vector<vector<int>>& A) {
int row = A.size(), col = A[0].size();
vector<vector<int>> id(row,vector<int>(col,0));
deque<pair<int,int>> q;
int island = 0, res = 0;
for(int i = 0; i < row; ++i)
for(int j = 0; j < col; ++j)
if(A[i][j] == 1 && id[i][j] == 0)
dfs(A, id, q, i, j, ++island);
while(!q.empty()){
int size = q.size();
for(int i = 0; i < size; ++i){
pair<int,int> x = q.front();
q.pop_front();
if(x.first > 0){
if(A[x.first - 1][x.second] == 0){
A[x.first - 1][x.second] = 1;
q.push_back(make_pair(x.first - 1,x.second));
}
else if(id[x.first - 1][x.second] == 2)
return res;
}
if(x.second > 0){
if(A[x.first][x.second - 1] == 0){
A[x.first][x.second - 1] = 1;
q.push_back(make_pair(x.first,x.second - 1));
}
else if(id[x.first][x.second - 1] == 2)
return res;
}
if(x.first < row - 1){
if(A[x.first + 1][x.second] == 0){
A[x.first + 1][x.second] = 1;
q.push_back(make_pair(x.first + 1,x.second));
}
else if(id[x.first + 1][x.second] == 2)
return res;
}
if(x.second < col - 1){
if(A[x.first][x.second + 1] == 0){
A[x.first][x.second + 1] = 1;
q.push_back(make_pair(x.first,x.second + 1));
}
else if(id[x.first][x.second + 1] == 2)
return res;
}
}
++res;
}
return res;
}
void dfs(vector<vector<int>>& A, vector<vector<int>>& id, deque<pair<int,int>>& q, int i, int j, int island){
if(A[i][j] == 0 || id[i][j] != 0)
return ;
id[i][j] = island;
if(island == 1)
q.push_back(make_pair(i,j));
if(i > 0)
dfs(A, id, q, i - 1, j, island);
if(j > 0)
dfs(A, id, q, i, j - 1, island);
if(i < A.size() -1)
dfs(A, id, q, i + 1, j, island);
if(j < A[0].size() - 1)
dfs(A, id, q, i, j + 1, island);
}
};