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.
思路:网上基本上都是动态规划的方法, 以当前点matrix[x][y] = '1' 为右下角的最大正方形的边长f(x,y) = min( f(x-1,y), f(x,y-1), f(x-1,y-1)) + 1,而以matrix[x][y] = '0'为右下角的最大正方形的边长都为0,所以要用一个二维数组d[][]在遍历matrix矩阵的过程中不断记录对应点处的最大正方形边长。也即:
当matrix(x,y)=1时d(x,y)
= min( d(x-1,y), d(x,y-1), d(x-1,y-1)) + 1,当matrix(x,y)=0时,d(x,y)=0。遍历完后找出最大的d(x,y)即可,当然也可以像程序中那样,在遍历过程中就不断保存最大值,这样就只需遍历一遍即可。
代码如下:
public class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix==null || matrix.length==0 || matrix[0].length==0){
return 0;
}
//矩阵的行数为m,列数为n
int m = matrix.length;
int n = matrix[0].length;
int max = 0;
int[][] d = new int[m][n];
//先把边上的d[][]初始化,初始化后d[i-1][j]...这些才能存在
for(int i=0;i<m;i++){
if(matrix[i][0]=='1'){
d[i][0] = 1;
max = 1;
}
}
for(int j=0;j<n;j++){
if(matrix[0][j]=='1'){
d[0][j] = 1;
max = 1;
}
}
//正式开始遍历,并不断记录最大值
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
if(matrix[i][j]=='0'){
d[i][j] = 0;
}else{
d[i][j] = Math.min(Math.min(d[i-1][j],d[i-1][j-1]),d[i][j-1])+1;
max = Math.max(max,d[i][j]);
}
}
}
return max*max;
}
}
参考博客:http://blog.youkuaiyun.com/xudli/article/details/46371673