Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int orangesRotting(vector<vector<int>>& grid) {
- queue<pair<int, int>> q;
- int rows = grid.size(), cols=grid[0].size();
- for(int i=0; i<rows; i++)
- for(int j=0; j<cols; j++)
- if(grid[i][j] == 2)
- q.push({i, j});
- int minutes = 0;
- int dir[4][2] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
- while(!q.empty()){
- int sz = q.size();
- int count = 0;
- for(int i=0; i<sz; i++){
- auto p = q.front();
- q.pop();
- for(int j=0; j<4; j++){
- int nextX = p.first+dir[j][0], nextY = p.second+dir[j][1];
- if(nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols || grid[nextX][nextY] != 1)
- continue;
- grid[nextX][nextY] = 2;
- q.push({nextX, nextY});
- count++;
- }
- }
- if(count)
- minutes++;
- }
- bool allRotten = true;
- for(int i=0; i<rows; i++)
- for(int j=0; j<cols; j++)
- if(grid[i][j] == 1)
- allRotten = false;
- return allRotten ? minutes : -1;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement