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:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0Return 4.
public class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix.length == 0||matrix[0].length ==0) return 0;
int m = matrix.length;
int n = matrix[0].length;
int[][] size = new int[m][n];
int maxsize = 0;
for(int j = 0; j < n; j++){
size[0][j] = matrix[0][j] - '0';
maxsize = Math.max(maxsize,size[0][j]);
}
for(int i = 1; i < m; i++){
size[i][0] = matrix[i][0] - '0';
maxsize = Math.max(maxsize,size[i][0]);
}
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
if(matrix[i][j] == '1'){
size[i][j] = Math.min(size[i-1][j-1],Math.min(size[i-1][j],size[i][j-1]))+1;
maxsize = Math.max(maxsize,size[i][j]);
}
}
}
return maxsize * maxsize;
}
}
https://leetcode.com/discuss/38489/easy-solution-with-detailed-explanations-8ms-time-and-space