-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path994. Rotting Oranges.cpp
48 lines (47 loc) · 1.33 KB
/
994. 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
class Solution {
public:
bool ispos(int a,int b,int m,int n,vector<vector<int>>& grid){
if(a<0||a>=m||b<0||b>=n){
return false;
}
if(grid[a][b]==1){
return true;
}
return false;
}
int orangesRotting(vector<vector<int>>& grid) {
queue<pair<int,int>> q;
for(int i=0;i<grid.size();i++){
for(int j=0;j<grid[0].size();j++){
if(grid[i][j]==2){
q.push({i,j});
}
}
}
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int ans=-1;
while(!q.empty()){
int sz=q.size();
while(sz--){
auto it=q.front();
q.pop();
for(int i=0;i<4;i++){
if(ispos(it.first+dx[i],it.second+dy[i],grid.size(),grid[0].size(),grid)){
grid[it.first+dx[i]][it.second+dy[i]]=2;
q.push({it.first+dx[i],it.second+dy[i]});
}
}
}
ans++;
}
for(int i=0;i<grid.size();i++){
for(int j=0;j<grid[0].size();j++){
if(grid[i][j]==1){
return -1;
}
}
}
return (ans==-1)?0:ans;
}
};