LeetCode 221. Maximal Square

DP问题,有点难想,但是理解以后不难。

记 dp[i][j] 为以 a[i][j] 为右下角的正方形的最大边长。

递推公式写起来不难,dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1       if a[i][j]==1

如下图所示,较小的边+1后形成的正方形一定是包含在其他图形中的,也就是说都是1。

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        // dp[i][j] the max side length when the bottom right corner of the square is matrix[i][j]
        // dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1       if a[i][j]==1
        
        
        int m=matrix.size(), n=m>0?matrix[0].size():0;
        vector<vector<int>> dp(m,vector<int>(n,0));
        int max_len=0;
        for (int i=0;i<m;++i){
            for (int j=0;j<n;++j){
                if (i==0 || j==0){
                    dp[i][j] = matrix[i][j]-'0';
                }
                else if (matrix[i][j]=='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;
    }
};

相关问题:85. Maximal Rectangle

猜你喜欢

转载自www.cnblogs.com/hankunyan/p/9545758.html