knakul853

Untitled

Jul 20th, 2020
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int orangesRotting(vector<vector<int>>& grid) {
  4.        
  5.         int n = (int)grid.size();
  6.         int m = (int)grid[0].size();
  7.        
  8.         queue<pair<int,int>>q;
  9.        
  10.         for(int i=0;i<n;i++){
  11.             for(int j=0;j<m;j++){
  12.                 if(grid[i][j] == 2){
  13.                     q.push({i, j});
  14.                 }
  15.             }
  16.         }
  17.        
  18.         int ans = 0;
  19.         if(q.size()) ans--;
  20.         int dx[4] = {1, -1, 0, 0};
  21.         int dy[4] = {0, 0, 1, -1};
  22.        
  23.         while( !q.empty() ){
  24.            
  25.         queue<pair<int,int>>temp;
  26.             int sz = q.size();
  27.                 ans++;
  28.            
  29.             for(int i=0;i<sz;i++){                
  30.                 auto node = q.front();q.pop();
  31.                 int x = node.first;
  32.                 int y = node.second;
  33.                
  34.                 for( int j=0;j<4;j++){
  35.                     int nx = x+dx[j];
  36.                     int ny = y+dy[j];
  37.                    
  38.                     if(nx < 0 || ny < 0 || nx >=n || ny >=m )continue;
  39.                     if(grid[nx][ny] == 0 || grid[nx][ny]==2)continue;
  40.                     grid[nx][ny] = 2;
  41.                    
  42.                     temp.push({nx, ny});
  43.                 }
  44.                
  45.             }
  46.            
  47.             q = temp;
  48.  
  49.         }
  50.        
  51.         for(int i=0;i<n;i++){
  52.             for(int j=0;j<m;j++){
  53.                 if(grid[i][j] == 1) return -1;
  54.             }
  55.         }
  56.        
  57.         return ans;
  58.        
  59.     }
  60. };
Add Comment
Please, Sign In to add comment