Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
rotting-oranges.cpp 1.24 KB
Copy Edit Raw Blame History
kamyu authored 2019-02-17 17:17 +08:00 . Create rotting-oranges.cpp
// Time: O(m * n)
// Space: O(m * n)
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
static const vector<pair<int, int>> directions{{0, 1}, {1, 0},
{0, -1}, {-1, 0}};
int count = 0;
queue<tuple<int, int, int>> q;
for (int r = 0; r < grid.size(); ++r) {
for (int c = 0; c < grid[r].size(); ++c) {
if (grid[r][c] == 2) {
q.emplace(r, c, 0);
} else if (grid[r][c] == 1) {
++count;
}
}
}
int result = 0;
while (!q.empty()) {
int r, c;
tie(r, c, result) = q.front(); q.pop();
for (const auto& d : directions) {
int nr = r + d.first, nc = c + d.second;
if (!(0 <= nr && nr < grid.size() &&
0 <= nc && nc < grid[r].size())) {
continue;
}
if (grid[nr][nc] == 1) {
--count;
grid[nr][nc] = 2;
q.emplace(nr, nc, result + 1);
}
}
}
return (count == 0) ? result : -1;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

Search