leecode_221 Maximal Square

来源:互联网 发布:程序员编程艺术 pdf 编辑:程序博客网 时间:2024/05/22 12:13

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.

For example, given the following matrix:

1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0

Return 4.

使用dp解决:

构造一个新的矩阵dp,dp[i][j]表示以点(i, j)为右下角的正方形的边长;状态转移方程:

dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;


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

0 0