-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrottenoranges.cpp
57 lines (51 loc) · 1.57 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
54
55
56
57
#include <bits/stdc++.h>
using namespace std;
int orangesRotting(vector<vector<int>> grid) {
if(grid.empty()) return 0;
int m = grid.size(), n = grid[0].size(), days = 0, tot = 0, cnt = 0;
queue<pair<int, int>> rotten;
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(grid[i][j] != 0) tot++;
if(grid[i][j] == 2) rotten.push({i, j});
}
}
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
while(!rotten.empty()){
int k = rotten.size();
cnt += k;
while(k--){
int x = rotten.front().first, y = rotten.front().second;
rotten.pop();
for(int i = 0; i < 4; ++i){
int nx = x + dx[i], ny = y + dy[i];
if(nx < 0 || ny < 0 || nx >= m || ny >= n || grid[nx][ny] != 1)
continue;
grid[nx][ny] = 2;
rotten.push({nx, ny});
}
}
if(!rotten.empty()) days++;
}
return tot == cnt ? days : -1;
}
int main()
{
int m,n;
cout<<"Enter the number of rows and columns: ";
cin>>m>>n;
vector<vector<int>> grid;
for(int i = 0; i < m; i++)
{
grid.push_back(vector<int>());
for(int j = 0; j < n; j++)
{
int z;
cin>>z;
grid[i].push_back(z);
}
}
cout<<orangesRotting(grid);
return 0;
}