Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
思路:dp[i][j]表示以坐标(i, j)为右下角元素的全1正方形矩阵的最大长度. 递推关系为:dp[i,j] = Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])+1; if matrix[i][j] = 0, dp[i][j] = 0.注意,如果本身为1,maxvalue也要设置为1.逻辑推理就是,只有附近的全部是1的时候,自己是1,才能往上增加1的边长,否则没办法组合成正方形。
class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int max = 0;
int n = matrix.length;
int m = matrix[0].length;
int[][] dp = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(matrix[i][j] == '0') {
dp[i][j] = 0;
} else {
// matrix[i][j] == '1';
dp[i][j] = 1;
if(i >= 1 && j >= 1) {
dp[i][j] = Math.min(dp[i][j-1], Math.min(dp[i-1][j-1], dp[i-1][j])) + 1;
}
max = Math.max(max, dp[i][j]);
}
}
}
return max * max;
}
}