问题链接:https://leetcode.com/problems/maximal-square/、
要求在二值矩阵中寻找最大全1正方形的面积。
思路一:一开始只能想到暴力搜索,代码如下
class Solution {
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 maxLength=Math.min(rows,cols);//可能的最大正方形长度为原数组行数和列数的较小值
for(int length=maxLength;length>0;length--)//可能的正方形长度为[length,1]
{
//正方形的搜索空间是由左上角顶点和右下角顶点坐标来唯一确定的,而左上角顶点的横纵坐标的取值范围是受到原矩阵行数和列数控制的,这里要小心的确定范围
for(int startRow=0;startRow<=rows-length;startRow++)
{
for(int startCol=0;startCol<=cols-length;startCol++)
{
if(isValid(matrix,startRow,startCol,startRow+length-1,startCol+length-1))
return length*length;
}
}
}
return 0;
}
public static boolean isValid(char[][] matrix,int ltx,int lty,int rbx,int rby)
{
for(int i=ltx;i<=rbx;i++)
{
for(int j=lty;j<=rby;j++)
{
if(matrix[i][j]=='0')
return false;
}
}
return true;
}
}
无疑这种暴力解法存在大量的冗余操作,运行效率自然很差。
思路二:看了题解https://leetcode.com/articles/maximal-square/的方法觉得惊为天人的感觉,这竟然也能DP,想不到,想不到,臣妾想不到呀!来欣赏一下这个动态规划算法,有时间再来详细研究这个算法到底是怎么思考出来的!
public class Solution {
public int maximalSquare(char[][] matrix) {
int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;
int[][] dp = new int[rows + 1][cols + 1];
int maxsqlen = 0;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
if (matrix[i-1][j-1] == '1'){
dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
maxsqlen = Math.max(maxsqlen, dp[i][j]);
}
}
}
return maxsqlen * maxsqlen;
}
}
时间和空间复杂度都是O(mn),效率提高了不少。
然后竟然有看到了更牛逼的Solutions,一维的DP,空间复杂度被优化到了O(m),收下我的膝盖!
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;
}
}