LeetCode934. 最短的橋

934. Shortest Bridge

[Medium] In a given 2D binary array A, 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: [[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. 1 <= A.length = A[0].length <= 100
  2. A[i][j] == 0 or A[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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章