-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotten Oranges
64 lines (58 loc) · 1.99 KB
/
Rotten Oranges
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
#include<bits/stdc++.h>
using namespace std;
int minTimeToRot(vector<vector<int>>& grid, int m, int n)
{
int vis[m+1][n+1];
memset(vis,0,sizeof(vis));
int cnt=0;
queue<pair<int,int>>q,q1;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(grid[i][j]==2&&vis[i][j]==0)
{
q.push({i,j});
}
}
}
int cnt1=0;
while(!q.empty())
{
int x=q.front().first;
int y=q.front().second;
q.pop();
grid[x][y]=2;
if(x+1<m&&vis[x+1][y]==0&&grid[x+1][y]==1)
{
q1.push({x+1,y});
vis[x+1][y]=1;
}
if(y+1<n&&vis[x][y+1]==0&&grid[x][y+1]==1)
q1.push({x,y+1}), vis[x][y+1]=1;
if(x>0&&vis[x-1][y]==0&&grid[x-1][y]==1)
q1.push({x-1,y}), vis[x-1][y]=1;
if(y>0&&vis[x][y-1]==0&&grid[x][y-1]==1)
q1.push({x,y-1}), vis[x][y-1]=1;
if(q.empty()&&!q1.empty())
{
cnt1++;
}
//cout<<x<<" "<<y<<q.size()<<endl;
if(q.empty())
while(!q1.empty())
{
q.push(q1.front());
q1.pop();
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(grid[i][j]==1)
return -1;
}
}
return cnt1;
}