Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.
Example
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]为最大正方形的右下角,则dp[i-1][j-1],dp[i-1][j],dp[i][j-1]是几个正方形的右下角。否则,dp[i][j]所属的正方形是自己。
正方形的边长:dp[i][j]是dp[i-1][j],dp[i-1][j-1],dp[i][j-1]中最小+1.
即dp[i][j]=min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1])+1;
#include <iostream>
using namespace std;
int dp[1005][1005],g[1005][1005];
int hs(int x,int y)
{
int s,i,j;
s=0;
for(i=0;i<x;i++)
for(j=0;j<y;j++)
{
dp[i][j]=(g[i][j]+1)%2;
s|=dp[i][j];
}
for(i=1;i<x;i++)
for(j=1;j<y;j++)
{
if(g[i][j])
dp[i][j]=0;
else
{
dp[i][j]=min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;
s=max(s,dp[i][j]);
}
}
return s*s;
}
int main()
{
int h,w;
int i,j;
cin>>h>>w;
for(i=0;i<h;i++)
for(j=0;j<w;j++)
cin>>g[i][j];
cout<<hs(h,w);
return 0;
}