E - Maximum Square

Description

Given an N x M matrix of all 1s and 0s, find the largest submatrix which is a square containing all 1s.

Input

There will be several test cases in the input. Each test case will begin with two integers, N and M (1N, M1, 000) indicating the number of rows and columns of the matrix. The next N lines will each contain M space-separated integers, guaranteed to be either 0 or 1. The input will end with a line with two 0s.

Output

For each test case, print a single integer, indicating the width (and height) of the largest square of all 1s, or 0 if there are no 1s. Print no extra spaces, and do not print any blank lines between answers.

Sample Input

4 5 
0 1 0 1 1 
1 1 1 1 1 
0 1 1 1 0 
1 1 1 1 1 
3 4 
1 1 1 1 
1 1 1 1 
1 1 1 1 
6 6 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0

Sample Output

3 
3 
0

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 1001
#define INF 2000

using namespace std;

int main()
{
    int n,m;
    char g[N][N];
    int ans[N][N];
    int L[N],H[N];
    while(scanf("%d%d",&n,&m),n!=0 || m!=0)
    {
        memset(g,0,sizeof(g));
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                scanf("%d",&g[i][j]);
        memset(ans,0,sizeof(ans));
        memset(L,0,sizeof(L));
        memset(H,0,sizeof(H));
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                if(g[i][j]==0) H[i]=0; else H[i]++;
                if(g[i][j]==0) L[j]=0; else L[j]=L[j]+1;
                if(H[i]>ans[i-1][j-1] && L[j]>ans[i-1][j-1]) ans[i][j]=ans[i-1][j-1]+1;
                else ans[i][j]=min(H[i],L[j]);
            }
        }
        int Max=-INF;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                Max=max(Max,ans[i][j]);
        printf("%d\n",Max);
    }
    return 0;
}


你可能感兴趣的:(Integer,input,each,Matrix,output)