Jul 15, 2024
n x m
where:
0
: Empty cell1
: Fresh orange2
: Rotten orange-1
if some fresh oranges can't be reached.-1
if any orange is unreachable.-1
.0
.n
and m
.0
.-1
if any fresh orange is left.#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void rottenOranges(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
queue<pair<pair<int, int>, int>> q; // store cell position and time
vector<vector<int>> visited(n, vector<int>(m, 0));
int freshCount = 0; // fresh oranges count
// Enqueue initial rotten oranges
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == 2) {
q.push({{i, j}, 0});
visited[i][j] = 1;
} else if (grid[i][j] == 1) {
++freshCount;
}
}
}
// Direction vectors for top, right, bottom, left
vector<int> dRow = {-1, 0, 1, 0};
vector<int> dCol = {0, 1, 0, -1};
int time = 0;
// BFS traversal
while (!q.empty()) {
auto cell = q.front(); q.pop();
int row = cell.first.first;
int col = cell.first.second;
int t = cell.second;
// Update the final time
time = max(time, t);
// Check all 4 possible neighbors
for (int i = 0; i < 4; ++i) {
int newRow = row + dRow[i];
int newCol = col + dCol[i];
// Check for valid cell and fresh orange
if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m &&
grid[newRow][newCol] == 1 && !visited[newRow][newCol]) {
q.push({{newRow, newCol}, t + 1});
visited[newRow][newCol] = 1;
--freshCount;
}
}
}
// If there are still fresh oranges left
if (freshCount > 0) {
cout << "-1" << endl;
} else {
cout << time << endl;
}
}
int main() {
vector<vector<int>> grid = {{2,1,1},{1,1,0},{0,1,1}};
rottenOranges(grid);
return 0;
}
O(n * m)
(queue and visited arrays).O(n * m)
traversing each cell and its 4 neighbors.-1
.