934. Shortest Bridge
[Medium] 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
題目:在給定的二維二進制數組 A
中,存在兩座島。(島是由四面相連的 1
形成的一個最大組。)現在,我們可以將 0
變爲 1
,以使兩座島連接起來,變成一座島。返回必須翻轉的 0
的最小數目。(可以保證答案至少是 1。)
思路:參考votrubac。將其中一座島先標記爲2,然後以該島爲中心,不斷外擴(同時標記)。
圖片轉自votrubac.
class Solution {
public:
int shortestBridge(vector<vector<int>>& A) {
int r = A.size();
int c = A[0].size();
for(int i = 0, found = 0; i < r && found == 0; ++i){
for(int j = 0; j < c && found == 0; ++j){
if(A[i][j] == 1){
found = paint(A, i, j);
}
}
}
for(int val = 2; ;++val){
for(int i = 0; i < r; ++i){
for(int j = 0; j < c; ++j){
if(A[i][j] == val && (expand(A,i+1,j,val) ||
expand(A,i-1,j,val) ||
expand(A,i,j+1,val) ||
expand(A,i,j-1,val)))
return val-2;
}
}
}
}
private:
int paint(vector<vector<int>>& A, int i, int j){
int r = A.size();
int c = A[0].size();
if(i < 0 || i >= r || j < 0 || j >= c || A[i][j] != 1)
return 0;
A[i][j] = 2;
return 1 + paint(A, i+1, j) + paint(A, i, j+1) +
paint(A, i-1, j) + paint(A, i, j-1);
}
bool expand(vector<vector<int>>& A, int i, int j, int val){
int r = A.size();
int c = A[0].size();
if(i < 0 || i >= r || j < 0 || j >= c)
return false;
if(A[i][j] == 0)
A[i][j] = val+1;
return A[i][j] == 1;
}
};