2022-4-19 Leetcode 542.01矩阵 —— 【人傻了,两次动态规划】

在这里插入图片描述
在这里插入图片描述

class Solution {
    
    
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
    
    

        if(mat.empty())
        return {
    
    {
    
    }};
        int m = mat.size();
        int 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(i > 0){
    
    
                        //从上到下
                        dp[i][j] = min(dp[i][j],dp[i-1][j]+1);
                    }
                    if(j > 0){
    
    
                        //从左到右
                        dp[i][j] = min(dp[i][j],dp[i][j-1]+1);
                    }
                }
            }
        }
        for(int i = m-1;i >= 0 ;i--){
    
    
            for(int j = n-1;j >= 0;j--){
    
    
                if(mat[i][j] == 0){
    
    
                    dp[i][j] = 0;
                }
                else{
    
    
                    if(i < m-1){
    
    
                        //从上到下
                        dp[i][j] = min(dp[i][j],dp[i+1][j]+1);
                    }
                    if(j < n-1){
    
    
                        //从左到右
                        dp[i][j] = min(dp[i][j],dp[i][j+1]+1);
                    }
                }
            }
        }
        return dp;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_51187533/article/details/124265847