《leetCode》: Maximal Square
题目
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 0
Return 4.
思路
对矩阵进行按列来进行处理,以例子来进行说明
1、第一步:开辟一个与矩阵列数相同的数组h
2、第二步:对矩阵的从第零行到第row-1行进行如下的两步处理:
3、第三步:对矩阵的第j行的所有元素进行判断,如果arr[i][j]==’1’,则h[j]++;否则h[j]=0;
4、第四步 :对h数组进行判断,寻找最大的面积(连续n个且元素值为n的数的面积为n^2)。例如:h={3,1,2,2}所代表的矩阵的最大面积为4.
版本一:不能AC
基于上面的思想,就有了这个版本。代码如下:
public class MaximalSquare_v1 {
public int maximalSquare(char[][] matrix) {
if(matrix == null||matrix.length==0){
return 0;
}
int row = matrix.length;
int col = matrix[0].length;
int [] h = new int[col];
int res = 0;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(matrix[i][j]=='1'){
h[j]++;
}
else{
h[j]=0;
}
}
res =Math.max(res, max(h));
}
return res;
}
/*
* 函数功能:找出n个连续值为n的数,则就是此时构成的最大正方形面积
* */
private int max(int[] h) {
if(h==null||h.length==0){
return 0;
}
//检查数组中是否全为零
int res =0;
for(int i=0;i<h.length;i++){
if(h[i]!=0){
res = 1;
break;
}
}
if(res==0){
return 0;
}
int count =1;
int startValue=h[0];
for(int i=1;i<h.length;i++){
if(h[i]!=startValue){
startValue = h[i];
count =1;
}
else{
count++;
if(count == startValue){
res = Math.max(res, count*startValue);
}
}
}
return res;
}
public static void main(String[] args){
MaximalSquare_v1 ms = new MaximalSquare_v1();
char [][] arr={
{'1','1','1','0','0'},
{'1','1','1','1','1'},
{'1','1','1','1','1'},
{'1','0','0','1','0'},
};
System.out.println(ms.maximalSquare(arr));
// int [] h={3,3,3,2,2};
// System.out.println(ms.max(h));
}
}
当遇到如下的矩阵时,以上代码不能AC,
原因在于:当h={3,2}这种情况时,以上的max(h)函数的结果为1,而实际上结果应该为4.基于此,在h数组中寻找最大值的方法为:h中有连续个n个数有大于等于n的数,则最大面积为n^2.
为达到上面的功能,有两种思路,第一种是:更改上面代码中max(h)函数中的算法思想,第二种是:不改变max(h)中的算法思想,在maximalSquare中添加一个while循环,来遍历matrix、以及去掉前i(0<=i
版本二:AC了
public class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix == null||matrix.length==0){
return 0;
}
int row = matrix.length;
int col = matrix[0].length;
int [] h = new int[col];
int res = 0;
int index =0;
while(index<row){
//从index行开始的矩阵构成的最大面积
//先清下零
for(int i=0;i<col;i++){
h[i] = 0;
}
for(int i=index;i<row;i++){
for(int j=0;j<col;j++){
if(matrix[i][j]=='1'){
h[j]++;
}
else{
h[j]=0;
}
}
res =Math.max(res, max(h));
}
index++;
}
return res;
}
/*
* 函数功能:找出n个连续值为n的数,则就是此时构成的最大正方形面积
* */
private int max(int[] h) {
if(h==null||h.length==0){
return 0;
}
//检查数组中是否全为零
int res =0;
for(int i=0;i<h.length;i++){
if(h[i]!=0){
res = 1;
break;
}
}
if(res==0){
return 0;
}
int count =1;
int startValue=h[0];
for(int i=1;i<h.length;i++){
if(h[i]!=startValue){
startValue = h[i];
count =1;
}
else{
count++;
if(count == startValue){
res = Math.max(res, count*startValue);
}
}
}
return res;
}
}
AC结果如下,从结果中可以看出,效率确实不高,所以最好的方法就是换max(h)中的算法。