/
994.腐烂的橘子.cpp
108 lines (106 loc) · 2.7 KB
/
994.腐烂的橘子.cpp
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
/*
* @lc app=leetcode.cn id=994 lang=cpp
*
* [994] 腐烂的橘子
*
* https://leetcode-cn.com/problems/rotting-oranges/description/
*
* algorithms
* Easy (46.82%)
* Likes: 147
* Dislikes: 0
* Total Accepted: 17.1K
* Total Submissions: 34.2K
* Testcase Example: '[[2,1,1],[1,1,0],[0,1,1]]'
*
* 在给定的网格中,每个单元格可以有以下三个值之一:
*
*
* 值 0 代表空单元格;
* 值 1 代表新鲜橘子;
* 值 2 代表腐烂的橘子。
*
*
* 每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。
*
* 返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1。
*
*
*
* 示例 1:
*
*
*
* 输入:[[2,1,1],[1,1,0],[0,1,1]]
* 输出:4
*
*
* 示例 2:
*
* 输入:[[2,1,1],[0,1,1],[1,0,1]]
* 输出:-1
* 解释:左下角的橘子(第 2 行, 第 0 列)永远不会腐烂,因为腐烂只会发生在 4 个正向上。
*
*
* 示例 3:
*
* 输入:[[0,2]]
* 输出:0
* 解释:因为 0 分钟时已经没有新鲜橘子了,所以答案就是 0 。
*
*
*
*
* 提示:
*
*
* 1 <= grid.length <= 10
* 1 <= grid[0].length <= 10
* grid[i][j] 仅为 0、1 或 2
*
*
*/
// @lc code=start
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int min = 0, fresh = 0;
//q为 rotten orange set
queue<pair<int, int>> q;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (grid[i][j] == 1)
fresh++;
else if (grid[i][j] == 2)
q.push(make_pair(i, j));
}
}
vector<pair<int, int>> directs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
while (!q.empty()) {
int n = q.size();
bool rotten = false;
//每一次循环,把所有的烂橘子拿出来看。
for (int i = 0; i < n; i++) {
auto x = q.front();
q.pop();
for (auto cur : directs) {
int i = x.first + cur.first;
int j = x.second + cur.second;
if (i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 1) {
grid[i][j] = 2;
q.push({i, j});
fresh--;
rotten = true;
}
}
}
if (rotten) min++;
}
return fresh ? -1 : min;
}
};
// @lc code=end