221. Maximal Square
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int rows = matrix.length, cols = matrix[0].length;
int[][] dp = new int[rows + 1][cols + 1];
int max = 0;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
if (matrix[i - 1][j - 1] == '1'){ // 注意这里,dp比matrix大一圈所以需要-1
// dp[i][j] is the smallest number + 1 in the closest square, where the current number is at the right bottom
dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
max = Math.max(max, dp[i][j]);
}
}
}
return max * max;
}Last updated