Largest Square
Given a matrix (H × W) which contains only 1 and 0, find the area of the largest square matrix which only contains 0s.
Input
H W c1,1 c1,2 ... c1,W c2,1 c2,2 ... c2,W : cH,1 cH,2 ... cH,W
In the first line, two integers H and W separated by a space character are given. In the following H lines, ci,j, elements of the H × W matrix, are given.
Output
Print the area (the number of 0s) of the largest square.
Constraints
- 1 ≤ H, W ≤ 1,400
Sample Input
4 5 0 0 1 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0
Sample Output
4
动态规划问题
#include<bits/stdc++.h>
using namespace std;
const int maxn=1400;
int dp[maxn][maxn],g[maxn][maxn];
int getlargestsquare(int h,int w)
{
int maxwidth=0;
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
dp[i][j]=(g[i][j]+1)%2;
//只有一行的情况
maxwidth|=dp[i][j];
}
}
for(int i=1;i<h;i++){
for(int j=1;j<w;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;
maxwidth=max(maxwidth,dp[i][j]);
}
}
}
return maxwidth*maxwidth;
}
int main()
{
int h,w;
cin>>h>>w;
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
cin>>g[i][j];
}
}
printf("%d\n",getlargestsquare(h,w));
return 0;
}