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;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Israel Lopez

    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));

    }

  • Alina Rozenbaum

    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?

  • Guest

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

    max = Math.min(min, max)