[LeetCode] Rotting Oranges

994. Rotting Oranges

You are given an m x n grid where each cell can have one of three values:

  • 0 representing an empty cell,
  • 1 representing a fresh orange, or
  • 2 representing 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.

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
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int dx[4]{0,1,0,-1}, dy[4]{-1,0,1,0};
int n = grid.size(), m = grid[0].size(), fresh = 0, day = 0;
bool beRot = true;
queue<pair<int, int>> q;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
switch (grid[i][j]) {
case 1 : fresh++; break;
case 2 : q.push({i,j}); break;
}
}
}

if(!fresh) return 0;
if(q.empty()) return -1;

while (beRot) {
beRot = false;
day++;
int sz = q.size();
while(sz--) {
auto p = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int nx = p.second + dx[i], ny = p.first + dy[i];
if(0 <= nx && nx < m && 0 <= ny && ny < n && grid[ny][nx] == 1) {
fresh--;
grid[ny][nx] = 2;
q.push({ny, nx});
beRot = true;
}
}
}
}


return fresh ? -1 : day - 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/07/PS/LeetCode/rotting-oranges/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.