-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRottenOranges.cpp
53 lines (48 loc) · 1.44 KB
/
RottenOranges.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
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int n=grid.size();
int m=grid[0].size();
// {{},time}
queue<pair<pair<int,int>,int>>q;
int visited[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(grid[i][j]==2){
q.push({{i,j},0});
visited[i][j]=2;
}
else{
visited[i][j]=0;
}
}
}
int timing=0;
int delrow[]={-1,0,+1,0};
int delcol[]={0,+1,0,-1};
while(!q.empty()){
int r=q.front().first.first;
int c=q.front().first.second;
int t=q.front().second;
timing=max(timing,t);
q.pop();
for(int i=0;i<4;i++){
int nrow=r+delrow[i];
int ncol=c+delcol[i];
if(nrow>=0 && nrow<n && ncol>=0 && ncol<m && visited[nrow][ncol]==0 && grid[nrow][ncol]==1){
q.push({{nrow,ncol},t+1});
visited[nrow][ncol]=2;
// move++;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(visited[i][j]!=2 && grid[i][j]==1){
return -1;
}
}
}
return timing;
}
};