forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotten_Oranges.cpp
148 lines (118 loc) · 2.43 KB
/
Rotten_Oranges.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/*
Each cell is represented by either
0: Empty cell
1: Cells have fresh oranges
2: Cells have rotten oranges
Only a fresh orange adjacent to a rotten one will get rotten after 1 second.
*/
#include <bits/stdc++.h>
using namespace std;
// A struct data type for storing each and every cell index pairs
struct cell
{
int x, y;
};
// Checks if the index in consideration is valid or not
bool isValid(int x, int y, int R, int C)
{
return (x >= 0 && x < R && y >= 0 && y < C);
}
// Checks if there are still some fresh oranges left
bool checkall(vector <int> arr[], int R)
{
int C = arr[0].size();
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
if (arr[i][j] == 1)
return true;
return false;
}
// A checker to take care of all corner case. In case the matrix is all zero then this checker takes care of such cases
bool checkzero(vector <int> arr[], int R)
{
int C = arr[0].size();
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
if (arr[i][j] != 0)
return false;
return true;
}
int rotOranges(vector <int> arr[], int R)
{
queue <cell> q;
cell curr;
int time = -1, lsize, x, y, i, j;
int xindex[] = {1, -1, 0, 0};
int yindex[] = {0, 0, 1, -1};
int C = arr[0].size();
for (i=0; i < R; i++)
for (j=0; j < C; j++)
if (arr[i][j] == 2)
q.push({i, j});
while (!q.empty())
{
time++;
lsize = q.size();
while (lsize--)
{
curr = q.front();
q.pop();
for (int i=0; i < 4; i++)
{
x = curr.x + xindex[i];
y = curr.y + yindex[i];
if (!isValid(x, y, R, C))
continue;
if (arr[x][y] == 1)
{
arr[x][y] = 2;
q.push({x, y});
}
}
}
}
if (checkzero(arr, R))
return 0;
if (checkall(arr, R))
return -1;
return time;
}
int main()
{
int R, C, num;
cout << "Enter number of rows and columns: ";
cin >> R >> C;
vector <int> arr[R];
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
{
cout << "\nEnter number : ";
cin >> num;
arr[i].push_back(num);
}
}
int ans = rotOranges(arr, 3);
if (ans != -1)
cout << "\nThe time taken is " << ans << " seconds.";
else
cout << "\nAll the oranges cannot be rotten !!";
return 0;
}
/*
Row = 3
Column = 5
Time t = 0
2, 1, 0, 2, 1
1, 0, 1, 2, 1
1, 0, 0, 2, 1
Time t = 1
2, 2, 0, 2, 2
2, 0, 2, 2, 2
1, 0, 0, 2, 2
Time t = 2
2, 2, 0, 2, 2
2, 0, 2, 2, 2
2, 0, 0, 2, 2
All oranges are rotten. Time taken is 2 seconds.
*/