LeetCode 994 - Rotting Oranges
Table of Contents
Problem Statement
You are given an m x n grid where each cell can have one of three values:
0representing an empty cell,1representing a fresh orange, or2representing a rotten orange.
Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
Using Breadth First Search
We can use Breadth-First Search (BFS) to simulate the rotting process of the oranges.
BFS Traversal:
- BFS allows rotting to propagate minute by minute, in all four directions, matching the problemβs requirement.
- BFS allows rotting to propagate minute by minute, in all four directions, matching the problemβs requirement.
Tracking Time:
- Each level of BFS represents one minute passing. We increment
minutesafter processing each level.
- Each level of BFS represents one minute passing. We increment
Edge Cases:
If there are no fresh oranges from the start, return
0.If some fresh oranges cannot be reached, return
-1.
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
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
queue<pair<int, int>> q;
int freshCount = 0;
int minutes = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 2) {
q.push({i, j});
} else if (grid[i][j] == 1) {
freshCount++;
}
}
}
vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
while (!q.empty() && freshCount > 0) {
int levelSize = q.size();
for (int i = 0; i < levelSize; i++) {
auto [x, y] = q.front();
q.pop();
for (auto [dx, dy] : directions) {
int nx = x + dx;
int ny = y + dy;
if (nx >= 0 && ny >= 0 && nx < m && ny < n && grid[nx][ny] == 1) {
grid[nx][ny] = 2;
q.push({nx, ny});
freshCount--;
}
}
}
minutes++;
}
return freshCount == 0 ? minutes : -1;
}
};
Complexity
Time Complexity: π(π Γ π)
- Every cell is visited at most once.
Space Complexity: π(π Γ π)
- Space used by the queue and auxiliary structures like the
directionsvector.
Conclusion
This BFS-based solution effectively simulates the rotting process and determines the minimum time required or detects when itβs impossible to rot all oranges.