Topic description
Find the largest square that does not contain 0 in an n*m matrix containing only 0 and 1, and output the side length.
Input and output format
Input format:The first line of the input file contains two integers n, m (1<=n, m<=100), the next n lines, each line contains m numbers, separated by spaces, 0 or 1.
Output format:an integer, the side length of the largest square
Input and output example
Solution:
This question is too watery ($Brave-Cattle$ giants ask me how to do this? ), direct two-dimensional prefixes and enumeration violence are $OK$.
$s[i][j]$ represents the sum of the numbers contained in the rectangle with $(1,1), (i,j)$ as the diagonal vertices, when the square with side length $a$ only contains $1$ , then the sum of the numbers in the square is $a^2$, so enumerate the side lengths from large to small, then enumerate the positions of the points, and judge $s[i][j]-s[i][ja ]-s[ia][j]+s[ia][ja]$ is equal to $a^2$. The time complexity $O(n^3)$ is completely passable.
Code:
1 #include<bits/stdc++.h> 2 #define For(i,a,b) for(int (i)=(a);(i)<=(b);(i)++) 3 using namespace std; 4 const int N=105; 5 int n,m,s[N][N],tot,x; 6 int main(){ 7 ios::sync_with_stdio(0); 8 cin>>n>>m; 9 For(i,1,n) { 10 tot=0; 11 For(j,1,m)cin>>x,tot+=x,s[i][j]+=s[i-1][j]+tot; 12 } 13 x=n>m?m:n; 14 while(x){ 15 For(i,x,n) For(j,x,m) 16 if(s[i][j]-s[i][j-x]-s[i-x][j]+s[i-x][j-x]==x*x){cout<<x;return 0;} 17 x--; 18 } 19 }