腐烂的橘子
在一开始需要把多个等价源点一起入队。
const int dx[] = {-1,0,1,0};
const int dy[] = {0,1,0,-1};
class Solution {
public:
typedef pair<int,int> P;
bool isOk(vector<vector<int>>& a){
int cnt = 0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(a[i][j]==1) return false;
}
}
return true;
}
int m, n;
int orangesRotting(vector<vector<int>>& a) {
queue<P> q;
m = a.size() , n = a[0].size();
if(isOk(a)) return 0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(a[i][j]==2){
q.push(make_pair(i,j));
}
}
}
int dpt = 1;
while(q.size()){
int size = q.size();
while(size--){
P p = q.front();
q.pop();
int x = p.first;
int y = p.second;
for(int k=0;k<4;k++){
int nx = x+dx[k];
int ny = y+dy[k];
if(nx>=0 && nx<m && ny>=0 && ny<n && a[nx][ny]==1){
a[nx][ny] = 2;
q.push(make_pair(nx,ny));
}
}
}
if(isOk(a)) return dpt;
dpt++;
}
return -1;
}
};