221. Maximal Square
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
My Solutions:
方法1:建立一个int[][] dp 储存正方形,长度和宽度比matrix大一圈。
Time: O(m * n); Space: O(m * n)
public 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;
}
方法2:在每一个matrix[i][j],以此点作为左上点,检查周围能否形成更大的square
Time: O(m * n); Space: O(1)
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
int max = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == '1') {
while (isSquare(matrix, i, j, max)) max++;
}
}
}
return max * max;
}
public boolean isSquare(char[][] matrix, int i, int j, int max) {
int row = i + max;
int col = j + max;
if (row >= matrix.length || col >= matrix[0].length) return false;
for (int x = i; x <= row; x++) {
for (int y = j; y <= col; y++) {
if (matrix[x][y] != '1') return false;
}
}
return true;
}
Last updated