-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathRotting Oranges.cpp
85 lines (73 loc) · 2.41 KB
/
Rotting Oranges.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
Solution by Rahul Surana
***********************************************************
You are given an m x n grid where each cell can have one of three values:
0 representing an empty cell,
1 representing a fresh orange, or
2 representing a rotten orange.
Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
***********************************************************
*/
#include <bits/stdc++.h>
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int m = grid.size(),n= grid[0].size();
queue<pair<int,int>> q;
set<pair<int,int>> s;
for(int i = 0; i < m ;i++){
for(int j = 0; j < n ;j++){
if(grid[i][j] == 2){
q.push({i,j});
}
else if(grid[i][j] == 1){
s.insert({i,j});
}
}
}
int ans=0;
queue<pair<int,int>> nq;
bool changed = false;
while(!q.empty()){
int x = q.front().first;
int y = q.front().second;
q.pop();
if(x > 0 && grid[x-1][y] == 1) {
grid[x-1][y] = 2;
s.erase({x-1,y});
nq.push({x-1,y});
changed = true;
}
if(x <m-1 && grid[x+1][y] == 1) {
grid[x+1][y] = 2;
s.erase({x+1,y});
nq.push({x+1,y});
changed = true;
}
if(y > 0 && grid[x][y-1] == 1) {
grid[x][y-1] = 2;
s.erase({x,y-1});
nq.push({x,y-1});
changed = true;
}
if(y < n-1 && grid[x][y+1] == 1) {
grid[x][y+1] = 2;
s.erase({x,y+1});
nq.push({x,y+1});
changed = true;
}
if(q.empty()){
if(changed){
ans++;
swap(q,nq);
changed = false;
}
else break;
}
cout << ans <<" ";
}
if(s.size() > 0) return -1;
return ans;
}
};