Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.
Example
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
.
public class Solution {
/**
* @param matrix: a matrix of 0 and 1
* @return: an integer
*/
public int maxSquare(int[][] matrix) {
int height = matrix.length;
if(height == 0) return 0;
int width = matrix[0].length;
if(width == 0) return 0;
int[][] res = new int[height][width];
int max = 0;
for(int i = 0; i < width; i++) {
res[0][i] = matrix[0][i];
max = Math.max(max, res[0][i]);
}
for(int i = 0; i < height; i++) {
res[i][0] = matrix[i][0];
max = Math.max(max, res[i][0]);
}
for(int i = 1; i < height; i++) {
for(int j = 1; j < width; j++) {
res[i][j] = matrix[i][j] == 1 ? Math.min(res[i - 1][j], Math.min(res[i][j - 1], res[i - 1][j - 1])) + 1 : 0;
max = Math.max(max, res[i][j]);
}
}
return max * max;
}
}