Question:
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 0
Return 4.
Thinking:
IIf the [i-1][j], [i][j-1] and [i-1][j-1] all have the same length of ‘1’ edge and the [i][j] is ‘1’, the length of the square can increase.
Solution:
public int maximalSquare(char[][] matrix) {
int m = matrix.length;
if (m == 0) return 0;
int n = matrix[0].length;
int res = 0;
int[][] opt = new int[m+1][n+1];
for (int i = 1; i <= m; i++){
for (int j = 1; j <= n; j++) {
if (matrix[i-1][j-1] == '1') {
opt[i][j] = Math.min(opt[i-1][j-1], Math.min(opt[i-1][j], opt[i][j-1])) + 1;
res = Math.max(res, opt[i][j]);
}
}
}
return res * res;
}