-
Notifications
You must be signed in to change notification settings - Fork 0
/
RottenOranges.cpp
71 lines (62 loc) · 1.16 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <bits/stdc++.h>
using namespace std;
const int R = 3;
const int C = 5;
bool issafe(int i, int j)
{
if (i >= 0 && i < R && j >= 0 && j < C)
return true;
return false;
}
int rotOranges(int v[R][C])
{
bool changed = false;
int no = 2;
while (true) {
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
if (v[i][j] == no) {
if (issafe(i + 1, j)
&& v[i + 1][j] == 1) {
v[i + 1][j] = v[i][j] + 1;
changed = true;
}
if (issafe(i, j + 1)
&& v[i][j + 1] == 1) {
v[i][j + 1] = v[i][j] + 1;
changed = true;
}
if (issafe(i - 1, j)
&& v[i - 1][j] == 1) {
v[i - 1][j] = v[i][j] + 1;
changed = true;
}
if (issafe(i, j - 1)
&& v[i][j - 1] == 1) {
v[i][j - 1] = v[i][j] + 1;
changed = true;
}
}
}
}
if (!changed)
break;
changed = false;
no++;
}
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
if (v[i][j] == 1)
return -1;
}
}
return no - 2;
}
int main()
{
int v[R][C] = { { 2, 1, 0, 2, 1 },
{ 1, 0, 1, 2, 1 },
{ 1, 0, 0, 2, 1 } };
cout << "Max time incurred: " << rotOranges(v);
return 0;
}