Skip to content

Commit c85feca

Browse files
committed
Add Rotten Oranges Graph Problem using BFS
1 parent dce9bd9 commit c85feca

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

src/cpp/RottenOranges.cpp

+103
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
/*
6+
Problem Statement:
7+
Given an m x n grid, where each cell has the following values:
8+
2 – Rotten orange
9+
1 – Fresh orange
10+
0 – Empty cell
11+
12+
Every minute, if a Fresh orange is adjacent to a Rotten Orange in 4-direction
13+
(upward, downwards, right, and left) it becomes Rotten.
14+
15+
Return the minimum number of minutes required such that
16+
none of the cells has a Fresh Orange.
17+
If it's not possible, return -1.
18+
*/
19+
20+
// Approach: BFS
21+
22+
bool isValid(int nx, int ny, int m, int n)
23+
{
24+
return (0 <= nx && nx < m) &&
25+
(0 <= ny && ny < n);
26+
}
27+
28+
// Time: O(mn) x 4
29+
// Space: O(mn)
30+
int orangesRotting(vector<vector<int>> &grid)
31+
{
32+
int m = grid.size();
33+
int n = grid[0].size();
34+
35+
int total = 0; // fresh + rotten oranges
36+
int count = 0; // rotten oranges
37+
int mins = 0; // minutes elapsed
38+
39+
queue<pair<int, int>> rotten; // {i, j}: position of rotten orange
40+
41+
// Count the fresh & rotten oranges, push rotten oranges into queue
42+
for (int i = 0; i < m; i++)
43+
{
44+
for (int j = 0; j < n; j++)
45+
{
46+
if (grid[i][j] != 0) // Rotten or Fresh orange
47+
total++;
48+
if (grid[i][j] == 2) // Rotten
49+
rotten.push({i, j}); // Push position of rotten orange
50+
}
51+
}
52+
53+
int dx[] = {0, 0, -1, 1}; // 4-directions (x-axis)
54+
int dy[] = {-1, 1, 0, 0}; // 4-directions (y-axis)
55+
56+
while (!rotten.empty())
57+
{
58+
int size = rotten.size(); // rotten oranges in current minute
59+
count += size; // add to total rotten oranges
60+
61+
while (size--) // Each rotten orange in current minute
62+
{
63+
// Pop the front rotten orange
64+
int x = rotten.front().first;
65+
int y = rotten.front().second;
66+
rotten.pop();
67+
68+
// Check for fresh oranges in 4-directions
69+
for (int i = 0; i < 4; i++)
70+
{
71+
// New coordinates
72+
int nx = x + dx[i];
73+
int ny = y + dy[i];
74+
75+
// Valid, fresh orange
76+
if (isValid(nx, ny, m, n) && grid[nx][ny] == 1)
77+
{
78+
grid[nx][ny] = 2; // make it rotten
79+
rotten.push({nx, ny}); // push it into queue
80+
}
81+
}
82+
}
83+
84+
if (!rotten.empty()) // if there are more rotten oranges
85+
mins++;
86+
}
87+
88+
if (total != count) // fresh oranges left
89+
return -1;
90+
91+
return mins;
92+
}
93+
94+
int main()
95+
{
96+
vector<vector<int>> grid = {{2, 1, 1},
97+
{1, 1, 0},
98+
{0, 1, 1}};
99+
100+
cout << orangesRotting(grid) << endl; // 4
101+
102+
return 0;
103+
}

0 commit comments

Comments
 (0)