Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 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组成的正方形的最大面积。

1、以每一个1作为左上角的顶点,然后想右边和下面扩展,看正方形有多大。

public class Solution {
    public int maximalSquare(char[][] matrix) {
        if (matrix.length == 0){
            return 0;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int result = 0;
        for (int i = 0; i < row; i++){
            for (int j = 0; j < col; j++){
                if (matrix[i][j] == '1'){
                    result = Math.max(result, getNum(matrix, i, j));
                }
            }
        }
        return result;
    }
    public int getNum(char[][] matrix, int row, int col){
        char ch = '1';
        int squre = 1;
        while (true){
            int num1 = row + squre;
            int num2 = col + squre;
            if (num1 >= matrix.length || num2 >= matrix[0].length){
                return squre * squre;
            }
            for (int i = row; i <= num1 ; i++){
                if (matrix[i][num2] != ch){
                    return squre * squre;
                }
            }
            for (int i = col; i <= num2; i++){
                if (matrix[num1][i] != ch){
                    return squre * squre;
                }
            }
            squre++;
        }
    }
    
 
    
}

 

 

2、dp:遇到一个1,然后看[i - 1][j], [i - 1][j - 1],[i][j - 1]的值是多少,取最小值,然后加1。记录期间出现的最大值。

 但是实际上没有第一种的速度快,因为有一个额外的row*col空间。

public class Solution {
    public int maximalSquare(char[][] matrix) {
        if (matrix.length == 0){
            return 0;
        }
        int result = 0;
        int[][] dp = new int[matrix.length + 1][matrix[0].length + 1];
        for (int i = 0; i < matrix.length; i++){
            for (int j = 0; j < matrix[0].length; j++){
                if (matrix[i][j] == '1'){
                    dp[i + 1][j + 1] = Math.min(Math.min(dp[i + 1][j], dp[i][j]), dp[i][j + 1]) + 1;
                    result = Math.max(result, dp[i + 1][j + 1]);
                }
            }
        }
        return result * result;
    }
}