Maximal Square (leetcode 221, lintcode 436)

重点:要仅在matrix[i][j] == 1时,更新状态方程,跳过等于0.

同时: 可以用[row+1][col+1]的方法来实现,并初始化[0][0]为0, 使得代码简洁。

     int maximalSquare(vector>& matrix) {
        if(matrix.empty() || matrix[0].empty()) return 0;
        int row = matrix.size(), col = matrix[0].size();
        
        vector> dp(row+1, vector(col+1, 0));
        
        int max_len = 0;
        for(int i=1; i<=row; i++){
            for(int j=1; j<=col; j++){
                if(matrix[i-1][j-1] == '1'){
                    dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;
                    max_len = max(max_len, dp[i][j]);
                }
            }
        }
        return max_len * max_len;
    }

sliding array to further reduce space complexity:
滚动数组的优化:注意,由于滚动数组并不能够做到对all row and all column的初始化了,所以matrix[i][j] == 0时不能跳过,要将dp[i][j]设为0;

class Solution {
public:
    /**
     * @param matrix: a matrix of 0 and 1
     * @return: an integer
     */
    int maxSquare(vector > &matrix) {
        // write your code here
        if(matrix.empty() || matrix[0].empty()) return 0;
        int row = matrix.size(), col = matrix[0].size();
        vector> dp(2, vector(col+1, 0));
        
        int max_len = 0;
        for(int i=1; i<=row; i++){
            for(int j=1; j<=col; j++){
                if(matrix[i-1][j-1] == 1){
                    dp[i%2][j] = min(dp[(i-1)%2][j-1], min(dp[(i-1)%2][j], dp[i%2][j-1])) + 1;
                    if(dp[i%2][j] > max_len) max_len = dp[i%2][j];
                }else{
                    dp[i%2][j] = 0;
                }
                
            }
        }
        return max_len * max_len;
    }
};

你可能感兴趣的:(Maximal Square (leetcode 221, lintcode 436))