Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 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 0Return 4.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
更好的方法:每个点填以这个点为左上角的最大方格。当一个点本身为1,同时下右和下右三个点都至少为n时,这个点给n+1
public class Solution {
private int maxLen(char[][] m,int l,int i,int j){//判断当前点最大方格,至少边长l
for(int x = i;x<i+l;x++){
for(int y = j; y< j+l;y++){
if(m[x][y]=='0')return 0;
}
}
while(i+l<m.length&&j+l<m[0].length){
for(int x = i;x<=i+l;x++){
if(m[x][j+l]=='0')return l;
}
for(int y = j;y<=j+l;y++){
if(m[j+l][y]=='0')return l;
}
l++;
}
return l;
}
public int maximalSquare(char[][] matrix) {
int hang = matrix.length;
if (hang==0)return 0;
int lie = matrix[0].length;
int maxl = 0;
// for(int i = 0;i<hang - maxl;i++){
// for(int j =0;j< lie - maxl;j++){
// }
// }
for(int i = hang-1;i>=0;i--){
for(int j = lie-1-maxl;j>=0;j--){
if(matrix[i][j]=='1'){
int a = maxLen(matrix,maxl+1,i,j);
if(a>maxl)maxl=a;
if(i>hang-1-maxl){i=hang-maxl-1;j=lie-maxl;if(i<0)break;}//下一轮进j=lie-maxl-1
}
}
}
return maxl*maxl;
}
}