class Solution {
public:
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int n = mat.size(), m = mat[0].size();
vector<vector<int>> res(n,vector<int>(m,INT_MAX));
queue<pair<int,int>> q;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (mat[i][j] == 0){
q.push({i,j});
res[i][j] = 0;
}
}
while (!q.empty()){
auto p = q.front(); q.pop();
for (int i = 0; i < 4; i++){
int x = p.first + dx[i], y = p.second + dy[i];
if (x < 0 || x >= n || y < 0 || y >= m) continue;
if (res[x][y] > res[p.first][p.second] + 1){
res[x][y] = res[p.first][p.second] + 1;
q.push({x,y});
}
}
}
return res;
}
};