标签:max image 代码 function ima 描述 idt origin view
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
if(matrix.empty()) return {};
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> dp(m, vector<int>(n, INT_MAX - 1));
// 1. 从左上到右下动态搜索;
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(matrix[i][j] == 0)
dp[i][j] = 0;
else{
// 注意j,i的顺序
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);
}
}
}
}
// 2. 从右下向左上动态搜索;
for(int i = m-1; i >= 0; --i){
for(int j = n-1; j >= 0; --j){
if(matrix[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