在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。
示例:
输入:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
输出: 4
转移方程 : dp[i][j] = min(dp[i-1][j],dp[i-1][j-1],dp[i][j-1])+1
class Solution {
public int maximalSquare(char[][] matrix) {
//定义 dp[i][j] 代表以这点为右下角 的 最大正方形 边长
// dp[i][j] = min(dp[i-1][j],dp[i-1][j-1],dp[i][j-1])+1
if(matrix==null){
return 0;
}
int row = matrix.length;//行? 代表第几排 y
if(row==0){
return 0;
}
int column = matrix[0].length;//列 ? 代表第几列 x
int dp [][] =new int [row+1][column+1];
int maxlength=0;
//从1,1 开始
for(int i=1;i<=row;i++){
for(int j=1;j<=column;j++){
if (matrix[i-1][j-1] == '1'){
dp[i][j] = Math.min(dp[i-1][j],Math.min(dp[i-1][j-1],dp[i][j-1]))+1;
maxlength =Math.max(maxlength,dp[i][j]);
}
}
}
return maxlength*maxlength;
}
}