问题:
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 11
1 0 0 1 0
Return 4.
解决:
① 动态规划。时间复杂度O(n^2),空间复杂度O(n^2)。
dp[i][j]表示以i,j为右下角的正方形的最大边长,则有:
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1
class Solution { //18ms
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0) return 0;
int m = matrix.length;
int n = matrix[0].length;
int max = 0;//最大边长
int[][] dp = new int[m][n];
for (int i = 0;i < m;i ++){//给第一列赋值
dp[i][0] = matrix[i][0] - '0';
max = Math.max(max,dp[i][0]);
}
for (int i = 0;i < n;i ++){//给第一行赋值
dp[0][i] = matrix[0][i] - '0';
max = Math.max(max,dp[0][i]);
}
for (int i = 1;i < m;i ++){
for (int j = 1;j < n;j ++){
dp[i][j] = matrix[i][j] == '1' ? Math.min(dp[i - 1][j - 1],Math.min(dp[i - 1][j],dp[i][j - 1])) + 1 : 0;
max = Math.max(max,dp[i][j]);
}
}
return max * max;
}
}
② 时间复杂度O(n^2),空间复杂度O(n)。
class Solution { //14ms
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
int m = matrix.length;
int n = matrix[0].length;
int max = 0;//最大边长
int[] nextRow = new int[n + 1];
for (int i = m - 1;i >= 0;i --){
int right = 0;
for (int j = n - 1;j >= 0;j --){
int len = 0;
if (matrix[i][j] == '1'){
len = Math.min(right,Math.min(nextRow[j],nextRow[j + 1])) + 1;
max = Math.max(len,max);
}
nextRow[j + 1] = right;
right = len;
}
nextRow[0] = right;
}
return max * max;
}
}