来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximal-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int maximalSquare(char[][] matrix) {
int maxSquare = 0;
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return 0;
}
int row = matrix.length;
int col = matrix[0].length;
// dp[i+1][j+1] 表示matrix 以(i,j)为右下角的矩形范围内,只包含1的最大正方形的边长
// dp[i+1][j+1] 取决于dp[i][j+1],dp[i+1][j]), dp[i][j]三者的最小值
// dp[i][j+1],dp[i+1][j]), dp[i][j]只要有一处为0,说明其左侧、上侧、左上角三者至少有一处是0,此时dp[i+1][j+1] 只能为0或者1;
// 范围是(row+1,col+1)是不用特殊考虑左侧和上方边界,
int[][] dp = new int[row+1][col+1];
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= col; j++) {
if(matrix[i-1][j-1] == '1') {
dp[i][j] = Math.min(Math.min(dp[i-1][j],dp[i][j-1]), dp[i-1][j-1]) + 1;
maxSquare = Math.max(maxSquare,dp[i][j]);
}
}
}
return maxSquare * maxSquare;
}
}
https://zhuanlan.zhihu.com/p/92355321
https://www.cnblogs.com/silentteller/p/12296974.html