题目描述:
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
Return 4.
采用动态规划,用dp[i][j]表示以matrix[i][j]为右下角的正方形的边长,如果matrix[i][j]=1,那么dp[i][j]=min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1])+1,否则dp[i][j]=0,然后取最大的pow(dp[i][j],2)即可。
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.size()==0) return 0;
if(matrix[0].size()==0) return 0;
vector<int> row(matrix[0].size(),0);
vector<vector<int>> dp(matrix.size(),row);
for(int i=0;i<matrix.size();i++)
{
if(matrix[i][0]=='0') dp[i][0]==0;
else dp[i][0]=1;
}
for(int j=0;j<matrix[0].size();j++)
{
if(matrix[0][j]=='0') dp[0][j]==0;
else dp[0][j]=1;
}
for(int i=1;i<matrix.size();i++)
{
for(int j=1;j<matrix[0].size();j++)
{
if(matrix[i][j]=='1')
dp[i][j]=min(min(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1])+1;
else dp[i][j]=0;
}
}
int result=INT_MIN;
for(int i=0;i<matrix.size();i++)
for(int j=0;j<matrix[0].size();j++)
result=max(result,dp[i][j]);
return pow(result,2);
}
};