题目链接:https://leetcode-cn.com/problems/rotting-oranges/
这道题刚开始看错题了,看到了图片就以为是就是从(0, 0)那个点开始,而且只有一个,然后敲完交了就wa了,然后才发现可能刚开始坏橘子有多个,而且还可能存在不连通的情况,所以就考虑多源bfs,刚开始将所有的坏橘子都扔进队列,然后bfs搜索就好了,不是很难,但是我的代码可能不太好读懂,我设置了一个嵌套pair的队列,也就是封装了三个参数,前两个是坐标,后一个是需要的天数( (.first.first, .first.second)这个表示坐标,.second表示需要的天数),然后将这个扔到队列中跑就好了,因为我在跑的过程中直接将新鲜的橘子变为坏橘子了,所以就没有用标记数组。
AC代码:
class Solution {
public:
typedef pair<int,int> p;
typedef pair<pair<int,int>, int> P;
queue<pair<pair<int,int>,int> > q;
int dir[4][2] = {1,0, 0,1, -1,0, 0,-1};
int bfs(vector<vector<int> >& g){
int n = g.size();
int m = g[0].size();
int cnt = 0;
int ans = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(g[i][j] == 2){
q.push(P(p(i, j), 0));
}
else if(g[i][j] == 1) cnt ++;
}
}
while(!q.empty()){
ans = max(ans, q.front().second);
for(int i=0;i<4;i++){
int x = q.front().first.first + dir[i][0];
int y = q.front().first.second + dir[i][1];
if(x >= 0 && y >= 0 && x < n && y < m && g[x][y] == 1){
g[x][y] = 2;
cnt --;
q.push(P(p(x, y), q.front().second + 1));
}
if(cnt == 0) break;
}
q.pop();
}
return cnt == 0 ? ans : -1;
}
int orangesRotting(vector<vector<int>>& g) {
return bfs(g);
}
};