-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path994. Rotting Oranges.cpp
67 lines (61 loc) · 1.75 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//https://leetcode.com/problems/rotting-oranges/submissions/
int orangesRotting(vector<vector<int>>& grid) {
int r=grid.size();
int c=grid[0].size();
queue<pair<pair<int,int>,int>> q;
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(grid[i][j]==2)
{
q.push({{i,j},0});
}
else if(grid[i][j]==1) grid[i][j]=-1;
}
}
int flag=1,ans=0;
while(!q.empty())
{
pair<int,int> p=q.front().first;
int z=q.front().second;
int x=p.first;
int y=p.second;
cout<<"x="<<x<<"y="<<y<<endl;
q.pop();
if(flag!=z) {ans++; flag=z;
}
if(x-1>=0 and grid[x-1][y]==-1)
{
grid[x-1][y]=1+grid[x][y];
q.push({{x-1,y},(1-z)});
}
if(x+1<r and grid[x+1][y]==-1)
{
grid[x+1][y]=1+grid[x][y];
q.push({{x+1,y},(1-z)});
}
if(y-1>=0 and grid[x][y-1]==-1)
{
grid[x][y-1]=1+grid[x][y];
q.push({{x,y-1},(1-z)});
}
if(y+1<c and grid[x][y+1]==-1)
{
grid[x][y+1]=1+grid[x][y];
q.push({{x,y+1},1-z});
}
}
if(ans>0)
ans=ans-1;
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
cout<<grid[i][j]<<" ";
if(grid[i][j]==-1) ans=-1;
}
cout<<endl;
}
return ans;
}