class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int m=grid.size(),n=grid[0].size();
queue<pair<int,int>>q;
int fresh=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]==2)q.push({i,j});
else if(grid[i][j]==1)fresh++;
}
}
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
int time=0;
while(!q.empty()){
bool flag=false;
int k=q.size();
for(int u=0;u<k;u++){
auto t=q.front();
q.pop();
for(int i=0;i<4;++i){
int x=t.first+dx[i],y=t.second+dy[i];
if(x>=0&&x<m&&y>=0&&y<n&&grid[x][y]==1){
grid[x][y]=2;
q.push({x,y});
flag=true;
fresh--;
}
}
}
if(flag)++time;
}
return fresh ? -1 : time;
}
};