LC 934. Shortest Bridge

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
Runtime:  40 ms, faster than 61.25% of C++ online submissions for Shortest Bridge.
class Solution {
private:
  int dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};

public:

  int dist(int x1, int x2, int y1, int y2){
    return abs(x1 - x2) + abs(y1 - y2);
  }

  int shortestBridge(vector<vector<int>>& A) {
//    cout << A.size() << endl;
//    cout << A[0].size() << endl;
    vector<vector<int>> t1, t2;
    bool found1 = false;
    for(int i=0; i<A.size(); i++){
      for(int j=0; j<A[0].size(); j++){
        if(A[i][j] == 1) {
          if(!found1) {
            found1 = true;
            helper(A, i, j, t1);
          }
          else helper(A, i, j, t2);
        }
      }
    }
    int mindist = INT_MAX;
    for(int i=0; i<t1.size(); i++){
      for(int j=0; j<t2.size(); j++){
        mindist = min(mindist, dist(t1[i][0], t2[j][0], t1[i][1], t2[j][1]));
      }
    }
    return mindist-1;
  }



  void helper(vector<vector<int>>& A, int x, int y, vector<vector<int>>& target) {
    A[x][y] = -1;
    for(int i=0; i<4; i++){
      int dx = x + dirs[i][0];
      int dy = y + dirs[i][1];
      if(dx >= 0 && dx < A.size() && dy >= 0 && dy < A[0].size() && A[dx][dy] == 0) {
        target.push_back({x,y});
        break;
      }
    }
    for(int i=0; i<4; i++){
      int dx = x + dirs[i][0];
      int dy = y + dirs[i][1];
      if(dx >= 0 && dx < A.size() && dy >= 0 && dy < A[0].size() && A[dx][dy] == 1) {
        helper(A, dx, dy, target);
      }
    }
  }
};

猜你喜欢

转载自www.cnblogs.com/ethanhong/p/10285686.html