1 题目
In a given grid, each cell can have one of three values:
- the value
0
representing an empty cell; - the value
1
representing a fresh orange; - the value
2
representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) 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
instead.
Example 1:
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
2 尝试解
2.1 分析
在格子里,有新鲜的橘子和坏掉的橘子。每一分钟内,坏掉的橘子会让周围(上下左右相邻格子里)的新鲜橘子也坏掉。问全部橘子都坏掉要多长时间。如果无解则返回-1。
典型的广度优先搜索算法,起始坏掉的橘子作为种子,每一分钟新被感染的橘子作为下一分钟的种子。直到所有可达的橘子都被感染。
2.2 代码
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int fresh = 0;
int minutes = 0;
queue<pair<int,int>> seeds;
for(int i = 0; i < grid.size();i++){
for(int j = 0; j <grid[0].size();j++){
if(grid[i][j]==1)
fresh++;
if(grid[i][j]==2)
seeds.push(make_pair(i,j));
}
};
if(fresh == 0) return 0;
while(seeds.size()){
queue<pair<int,int>> new_seeds;
while(seeds.size()){
pair<int,int> cur = seeds.front();
seeds.pop();
if(cur.first>0 && grid[cur.first-1][cur.second]==1){
fresh -= 1;
grid[cur.first-1][cur.second] = 2;
new_seeds.push(make_pair(cur.first-1,cur.second));
}
if(cur.first < grid.size()-1 && grid[cur.first+1][cur.second]==1){
fresh -= 1;
grid[cur.first+1][cur.second] = 2;
new_seeds.push(make_pair(cur.first+1,cur.second));
}
if(cur.second>0 && grid[cur.first][cur.second-1]==1){
fresh -= 1;
grid[cur.first][cur.second-1] = 2;
new_seeds.push(make_pair(cur.first,cur.second-1));
}
if(cur.second < grid[0].size()-1 && grid[cur.first][cur.second+1]==1){
fresh -= 1;
grid[cur.first][cur.second+1] = 2;
new_seeds.push(make_pair(cur.first,cur.second+1));
}
}
if(new_seeds.size()) minutes += 1;
seeds.swap(new_seeds);
}
if(fresh) return -1;
else return minutes;
}
};
3 标准解
class Solution {
public:
int rot(vector<vector<int>>& g, int i, int j, int d) {
if (i < 0 || j < 0 || i >= g.size() || j >= g[i].size() || g[i][j] != 1) return 0;
g[i][j] = d + 3;
return 1;
}
int orangesRotting(vector<vector<int>>& g, int d = 0, int fresh = 0) {
for (auto i = 0; i < g.size(); ++i)
fresh += count_if(begin(g[i]), end(g[i]), [](int j) { return j == 1; });
for (auto old_fresh = fresh; fresh > 0; ++d) {
for (auto i = 0; i < g.size(); ++i)
for (auto j = 0; j < g[i].size(); ++j)
if (g[i][j] == d + 2)
fresh -= rot(g,i+1,j,d) + rot(g,i-1,j,d) + rot(g,i,j+1,d) + rot(g,i,j-1,d);
if (fresh == exchange(old_fresh, fresh)) return -1;
}
return d;
}
};