同样的DP思想,转移方程是:
如果当前格是‘1’ 则取 “上”, “左”,“左上” 三个dp最小值+1
如果当前格是‘0’ 则为0
一开始尝试的是,如果当前格为0,则继承左,上,和左上三个点的最小值不加1,但是逻辑明显有漏洞。还是需要在dp循环中更新最长边,而不是直接取dp[-1]
class Solution {
public int maximalSquare(char[][] matrix) {
int row = matrix.length;
if (row == 0){
return 0;
}
int col = matrix[0].length;
int[][] dp = new int[row+1][col+1];
int maxSide = 0;
for(int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
if (matrix[i][j] == '1'){
dp[i+1][j+1] = Math.min(Math.min(dp[i][j+1], dp[i+1][j]), dp[i][j])+1;
maxSide = Math.max(maxSide, dp[i+1][j+1]);
}
}
}
return maxSide*maxSide;
}
}