Advertisement
nikunjsoni

994

May 2nd, 2021
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int orangesRotting(vector<vector<int>>& grid) {
  4.         queue<pair<int, int>> q;
  5.         int rows = grid.size(), cols=grid[0].size();
  6.        
  7.         for(int i=0; i<rows; i++)
  8.             for(int j=0; j<cols; j++)
  9.                 if(grid[i][j] == 2)
  10.                     q.push({i, j});
  11.  
  12.         int minutes = 0;
  13.         int dir[4][2] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
  14.        
  15.         while(!q.empty()){
  16.             int sz = q.size();
  17.             int count = 0;
  18.             for(int i=0; i<sz; i++){
  19.                 auto p = q.front();
  20.                 q.pop();
  21.                 for(int j=0; j<4; j++){
  22.                     int nextX = p.first+dir[j][0], nextY = p.second+dir[j][1];
  23.                     if(nextX < 0 || nextX >= rows || nextY < 0  || nextY >= cols || grid[nextX][nextY] != 1)
  24.                         continue;
  25.                     grid[nextX][nextY] = 2;
  26.                     q.push({nextX, nextY});
  27.                     count++;
  28.                 }
  29.             }
  30.             if(count)
  31.                 minutes++;
  32.         }
  33.        
  34.         bool allRotten = true;
  35.         for(int i=0; i<rows; i++)
  36.             for(int j=0; j<cols; j++)
  37.                 if(grid[i][j] == 1)
  38.                     allRotten = false;
  39.        
  40.         return allRotten ? minutes : -1;
  41.     }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement