LeetCode – Maximal Square (Java)

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:

1101
1101
1111

Return 4.

Analysis

This problem can be solved by dynamic programming. The changing condition is:
t[i][j] = min(t[i][j-1], t[i-1][j], t[i-1][j-1]) + 1. It means the square formed before this point.

Java Solution

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

4 thoughts on “LeetCode – Maximal Square (Java)”

  1. other solutions ( worse) would be

    ver1 force , for each sub matrix, check all 1
    ver2 force +hashing, hash each row/column , exist 0 or not
    then, for each submatrix(x,y, size m*n) check exist hashed 0 or not per row , column

  2. I Think it is a better solution.

    private static void process (int[][] arrray){

    int max=0, maxAux=0, maxRow=0, maxAuxRow=0;
    HashSet complete = new HashSet();

    for (int rows= 0; rows<arrray.length;rows++){

    max=0; maxAux=0;
    for (int cols = 0; colsmaxAux){
    maxAux = max;
    max = 0;
    }else if (maxAux>max){
    max = maxAux;
    maxAux = 0;
    }
    }

    maxRow =Math.max(max, maxAux);
    complete.add(Math.max(max, maxAux));

    }

    if (maxRow>maxAuxRow){
    maxAuxRow = maxRow;
    maxRow = 0;
    }else if (maxAuxRow>maxRow){
    maxRow = maxAuxRow;
    maxAuxRow = 0;
    }

    }

    System.out.println(“max “+Math.max(maxRow, maxAuxRow));

    }

  3. Ok, this may be stupidly redundant, but with a lot of the matrices problems, why not just pass as int[][], why do char[][] and then spend your time converting back in the method?

  4. Why can’t we keep track of max and update it inside ‘if (matrix[i][j] == ‘1’)’ with

    max = Math.min(min, max)

Leave a Comment