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 || matrix[0].length == 0)
		return 0;
 
	int m = matrix.length;
	int n = matrix[0].length;
 
	int[][] t = new int[m][n];
 
	//top row
	for (int i = 0; i < m; i++) {
		t[i][0] = Character.getNumericValue(matrix[i][0]);
	}
 
	//left column
	for (int j = 0; j < n; j++) {
		t[0][j] = Character.getNumericValue(matrix[0][j]);
	}
 
	//cells inside
	for (int i = 1; i < m; i++) {
		for (int j = 1; j < n; j++) {
			if (matrix[i][j] == '1') {
				int min = Math.min(t[i - 1][j], t[i - 1][j - 1]);
				min = Math.min(min,t[i][j - 1]);
				t[i][j] = min + 1;
			} else {
				t[i][j] = 0;
			}
		}
	}
 
	int max = 0;
	//get maximal length
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			if (t[i][j] > max) {
				max = t[i][j];
			}
		}
	}
 
	return max * max;
}
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)