-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotting_Oranges.cpp
More file actions
57 lines (52 loc) · 1.44 KB
/
Rotting_Oranges.cpp
File metadata and controls
57 lines (52 loc) · 1.44 KB
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
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize ("-O3")
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid)
{
vector<int> dir={-1,0,1,0,-1}; //used for finding all 4 adjacent coordinates
int m=grid.size();
int n=grid[0].size();
queue<pair<int,int>> q;
int fresh=0; //To keep track of all fresh oranges left
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(grid[i][j]==2)
q.push({i,j});
if(grid[i][j]==1)
fresh++;
}
int ans=-1;
while(!q.empty())
{
int sz=q.size();
while(sz--)
{
pair<int,int> p=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int r=p.first+dir[i];
int c=p.second+dir[i+1];
if(r>=0 && r<m && c>=0 && c<n &&grid[r][c]==1)
{
grid[r][c]=2;
q.push({r,c});
fresh--;
}
}
}
ans++;
}
if(fresh>0) return -1;
if(ans==-1) return 0;
return ans;
}
};
int main(){
ios_base::sync_with_stdio(0);
cin.tie(NULL); cout.tie(NULL);
return 0;
}