Advertisement
nikunjsoni

934

May 10th, 2021
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int n, m;
  4.     int dir[4][2] = {{-1,0}, {0,-1}, {0,1}, {1,0}};
  5.     int shortestBridge(vector<vector<int>>& A) {
  6.         n=A.size(); m =A[0].size();
  7.        
  8.         // Flood fill one island.
  9.         bool found = false;
  10.         for(int i=0; i<n && !found; i++)
  11.             for(int j=0; j<m && !found; j++)
  12.                 if(A[i][j]){
  13.                     found = true;
  14.                     fill(A, i, j, 2);
  15.                 }
  16.      
  17.         // BFS on border cells.
  18.         queue<pair<int, int>> q;
  19.         for(int i=0; i<n; i++)
  20.             for(int j=0; j<m; j++)
  21.                 if(A[i][j] == 2)
  22.                     q.push({i, j});
  23.        
  24.         int steps = 0;
  25.         while(!q.empty()){
  26.             int sz = q.size();
  27.             for(int i=0; i<sz; i++){
  28.                 auto p = q.front(); q.pop();
  29.                 int x = p.first, y = p.second;
  30.                 for(int j=0; j<4; j++){
  31.                     int nextX = x+dir[j][0], nextY = y+dir[j][1];
  32.                     if(nextX < 0 || nextX >= n || nextY < 0 || nextY >= m || A[nextX][nextY] == 2) continue;
  33.                     if(A[nextX][nextY] == 1) return steps;
  34.                     A[nextX][nextY] = 2;
  35.                     q.push({nextX, nextY});
  36.                 }
  37.             }
  38.             steps++;
  39.         }
  40.         return steps;
  41.     }
  42.    
  43.     void fill(vector<vector<int>>& A, int x, int y, int col){
  44.         A[x][y] = col;
  45.         for(int i=0; i<4; i++){
  46.             int nextX = x+dir[i][0], nextY = y+dir[i][1];
  47.             if(nextX < 0 || nextX >= n || nextY < 0 || nextY >= m || A[nextX][nextY] != 1 || A[nextX][nextY] == 0) continue;
  48.             fill(A, nextX, nextY, col);
  49.         }
  50.     }
  51.    
  52. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement