




#include <vector> // both m*n
#include <queue>
using namespace std;
class Solution {
public:
int orangesRotting(vector<vector<int>>& g) {
int m = g.size(), n = g[0].size();
queue<pair<int, int>> q;
int fresh = 0;
for(int r = 0 ; r < m ; ++r)
for(int c = 0 ; c < n ; ++c)
if(g[r][c]==2) q.push({r,c});
else if(g[r][c] == 1)fresh++;
int minutes = 0;
int dx[4]={1, -1, 0, 0};
int dy[4]={0, 0, 1, -1};
while(!q.empty() && fresh > 0){
int sz = q.size();
while(sz--){
auto[x, y]=q.front();q.pop();
for(int k = 0; k < 4; ++k){
int nx = x + dx[k], ny = y + dy[k];
if(nx >= 0 && nx < m && ny >= 0 && ny <n && g[nx][ny] == 1){
g[nx][ny]=2;
fresh--;
q.push({nx, ny});
}
}
}
minutes++;
}
return fresh==0?minutes:-1;
}
};