-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRottenOranges.cpp
More file actions
92 lines (76 loc) · 1.67 KB
/
RottenOranges.cpp
File metadata and controls
92 lines (76 loc) · 1.67 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <bits/stdc++.h>
using namespace std;
int rottenOranges(vector<vector<int>> &grid)
{
int n = grid.size();
int m = grid[0].size();
int count = 0;
int total = 0;
int days = 0;
queue<pair<int, int>> rotten;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (grid[i][j] != 0)
{
total++;
}
if (grid[i][j] == 2)
{
rotten.push({i, j});
}
}
}
int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};
while(!rotten.empty())
{
int k = rotten.size();
count+=k;
while(k--)
{
int x = rotten.front().first;
int y = rotten.front().second;
rotten.pop();
for(int i=0;i<4;i++)
{
int nrow = x+dx[i];
int ncol = y+dy[i];
if(nrow>=0 && nrow<n && ncol>=0 && ncol<m && grid[nrow][ncol]==1)
{
grid[nrow][ncol]=2;
rotten.push({nrow,ncol});
}
}
}
if(!rotten.empty())
{
days++;
}
}
if(total==count)
{
return days;
}else{
return -1;
}
}
int main()
{
int n, m;
cin >> n >> m;
vector<vector<int>> grid(n, vector<int>(m, -1));
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> grid[i][j];
}
}
int ans = rottenOranges(grid);
cout << ans << endl;
}
// Complexity Analysis
// Space Complexity -> O(N*M) + O(N*M)
// Time Complexity -> O(N*M + N*M*4)