• 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);
          }
        }
      }
    };
  • 相关阅读:
    安卓自动化测试添加用例执行回放
    【十二省2019】异或粽子
    【BZOJ4260】Codechef REBXOR
    【JSOI2015】字符串树
    【HAOI2017】供给侧改革
    【NOI2018】你的名字
    【十二省2019】字符串问题
    【LOJ#6041】事情的相似度
    【SP8093】JZPGYZ
    【BZOJ1396】识别子串
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10285686.html
Copyright © 2020-2023  润新知