BFS过了
class Solution {
public:
vector<int> dir{-1,0,1,0,-1};
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
queue<pair<int,int>> q;
vector<vector<bool>> visited(m,vector<bool>(n,false));
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(mat[i][j] == 0){
visited[i][j] = true;
q.push({i,j});
}
}
}
while(!q.empty()){
auto [i,j] = q.front();
q.pop();
for(int k = 0; k < dir.size()-1; k++){
int x = i + dir[k];
int y = j + dir[k+1];
if(x >= 0 && x < m && y >= 0 && y < n && !visited[x][y]){
mat[x][y] = mat[i][j] + 1;
visited[x][y] = true;
q.push({x,y});
}
}
}
return mat;
}
};
dp
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
vector<vector<int>> dp(m, vector<int>(n, INT_MAX - 1));
for(int i = 0; i < m; i ++){
for(int j = 0; j < n; j ++){
if(mat[i][j] == 0){
dp[i][j] = 0;
}
else{
if(j > 0)
dp[i][j] = min(dp[i][j], dp[i][j-1] + 1);
if(i > 0)
dp[i][j] = min(dp[i][j], dp[i-1][j] + 1);
}
}
}
for(int i = m-1; i >= 0; i--){
for(int j = n-1; j >= 0; j--){
if(mat[i][j] != 0){
if(j < n-1)
dp[i][j] = min(dp[i][j], dp[i][j+1] + 1);
if(i < m -1)
dp[i][j] = min(dp[i][j], dp[i+1][j] + 1);
}
}
}
return dp;
}
};
https://leetcode-cn.com/problems/01-matrix/solution/01ju-zhen-by-leetcode-solution/