← Back to Codes
C++
Rotten Oranges
Uses BFS to find the minimum time required to rot all oranges in a grid.
rotten_oranges.cpp
#include <iostream>
#include <vector>
#include <queue>
#include <tuple>
using namespace std;
int main() {
cout << "INSTRUCTIONS: Enter dimensions N and M, then the grid (0=Empty, 1=Fresh, 2=Rotten)." << endl;
int n, m;
cin >> n >> m;
vector<vector<int>> grid(n, vector<int>(m));
queue<pair<int,int>> q;
int fresh = 0, time = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
cin >> grid[i][j];
if (grid[i][j] == 2) q.push({i, j});
if (grid[i][j] == 1) fresh++;
}
int dirs[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
while (!q.empty() && fresh) {
int sz = q.size();
while (sz--) {
auto [x, y] = q.front(); q.pop();
for (auto& d : dirs) {
int nx = x + d[0], ny = y + d[1];
if (nx>=0 && ny>=0 && nx<n && ny<m && grid[nx][ny]==1) {
grid[nx][ny] = 2;
fresh--;
q.push({nx, ny});
}
}
}
time++;
}
cout << (fresh ? -1 : time);
}Rotten Oranges — Free C++, C, Python Code Example
Uses BFS to find the minimum time required to rot all oranges in a grid. This free code example is available in C++, C, Python and can be copied and run immediately — no account or signup required. Use the language tabs above to switch between implementations.
How to Use This Code
- Select your language — click the language tab (C, Java, C++, or Python) above the code viewer.
- Copy the code — use the copy button in the top-right corner of the code block.
- Run it — paste into a file with the correct extension (.c, .java, .cpp, .py), compile, and run using your terminal or IDE.
- Follow the on-screen instructions in the terminal to provide any required inputs.
Frequently Asked Questions
What does this program do?
Uses BFS to find the minimum time required to rot all oranges in a grid.
Which languages is it available in?
Available in C++, C, Python. Switch between implementations using the tabs at the top of the code viewer.
How do I run this code?
Copy the code, save it with the right file extension (.c, .java, .cpp, or .py), then compile or run it with your installed compiler or interpreter (GCC, JDK, G++, Python 3).
Is this code free?
Yes — free to view, copy, and use. No account required.