LeetCode 221.最大正方形

在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。

示例:

输入:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

输出: 4
算法:动态规划

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        if(!matrix.size())return 0;
        if(!matrix[0].size())return 0;
        int n=matrix.size(),m=matrix[0].size();
        int res=0;
        vector<vector<int>>dp(n+1,vector<int>(m+1,0));
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++){
                if(matrix[i][j]=='0')dp[i][j]=0;
                else{
                    dp[i][j]=1;
                    if(i&&j)
                        dp[i][j]+=min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]));
                    res=max(res,dp[i][j]);
                }
            }
        return res*res;
    }
};

 

posted @ 2019-07-20 13:41  YF-1994  阅读(135)  评论(0编辑  收藏  举报