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
题意:找出矩阵中全部由1组成的最大正方形的体积。
思路:从(0,0)开始,使用一个二维数组dp[][]记录矩阵中每行每列能与左上方组成的最大正方形边长。
以红色标记的(4,2)为例,左边最长边长为0,上边最长边长为2,左上能组成最长边长为1,所以只能以自身组成一个正方形,边长为1;
以绿色组成的(2,3)为例,左边最长边长为2,上边最长边长为2,左上能组成最长边长为2,所以加上自身就能组成一个边长为3的正方形;
以黄色组成的(3,4)为例,左边最长边长为3,上边最长边长为1,左上能组成最长边长为3,所以加上自身只能组成一个边长为2的正方形;
根据观察可得出结论:取dp数组中当前位置的左、上、左上三个的最小值,然后加上自身就是当前位置能组成的最大正方形。
代码:
class Solution {
public int maximalSquare(char[][] matrix) {
int m = matrix.length,n=m?matrix[0].length:0;
int size =0;
int [][]dp = new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(j==0 || i==0 || matrix[i][j] == '0'){
dp[i][j] = matrix[i][j] - '0';
}else{
dp[i][j] = Math.min(Math.min(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1]) +1 ;
}
size = Math.max(size,dp[i][j]);
}
}
return size*size;
}
}
官方给出更优解决方案及代码,值得学习:
In the previous approach for calculating dp of i^{th}ith row we are using only the previous element and the (i-1)^{th}(i−1)th row. Therefore, we don't need 2D dp matrix as 1D dp array will be sufficient for this.
Initially the dp array contains all 0's. As we scan the elements of the original matrix across a row, we keep on updating the dp array as per the equation dp[j]=min(dp[j-1],dp[j],prev)dp[j]=min(dp[j−1],dp[j],prev), where prev refers to the old dp[j-1]dp[j−1]. For every row, we repeat the same process and update in the same dp array.
public class Solution {
public int maximalSquare(char[][] matrix) {
int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;
int[] dp = new int[cols + 1];
int maxsqlen = 0, prev = 0;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
int temp = dp[j];
if (matrix[i - 1][j - 1] == '1') {
dp[j] = Math.min(Math.min(dp[j - 1], prev), dp[j]) + 1;
maxsqlen = Math.max(maxsqlen, dp[j]);
} else {
dp[j] = 0;
}
prev = temp;
}
}
return maxsqlen * maxsqlen;
}
}