Advertisement
nikunjsoni

286

May 1st, 2021
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     void wallsAndGates(vector<vector<int>>& rooms) {
  4.         int dir[4][2] = {{1,0},{0,1},{0,-1},{-1,0}};
  5.         queue<pair<int, int>> q;
  6.         int rows = rooms.size(),  cols = rooms[0].size();
  7.        
  8.         // Add all gates to queue.
  9.         for(int i=0; i<rows; i++)
  10.             for(int j=0; j<cols; j++)
  11.                 if(rooms[i][j] == 0)
  12.                     q.push({i, j});
  13.        
  14.         while(!q.empty()){
  15.             auto p = q.front(); q.pop();
  16.             int currX = p.first, currY = p.second, currDist = rooms[currX][currY];
  17.            
  18.             // Iterate in all possible directions.
  19.             for(int i=0; i<4; i++){
  20.                 int nextX = currX + dir[i][0], nextY = currY + dir[i][1];
  21.                 if(nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) continue;
  22.                 if(rooms[nextX][nextY] > currDist+1){
  23.                     rooms[nextX][nextY] = currDist+1;
  24.                     q.push({nextX, nextY});
  25.                 }
  26.             }
  27.         }
  28.     }
  29. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement