1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
return 4
// O(mn) space
public class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix == null || matrix.length == 0) return 0;
int m = matrix.length, n = matrix[0].length;
// right-bottom corner of square, and its width
int[][] dp = new int[m+1][n+1];
int width = 0;
for(int i=1; i<=m; i++){
for(int j=1; j<=n; 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;
width = Math.max(width, dp[i][j]);
} else dp[i][j] = 0;
}
}
return width*width;
}
}
// 只和上一层有关系,可以用O(n)空间,只记录上一层
public class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix == null || matrix.length == 0) return 0;
int m = matrix.length, n = matrix[0].length;
// right-bottom corner of square, and its width
int[] dp1 = new int[n+1];
int width = 0;
for(int i=0; i<m; i++){
int[] dp2 = new int[n+1];
for(int j=0; j<n; j++){
if(matrix[i][j] == '1'){
dp2[j+1] = Math.min(Math.min(dp1[j], dp1[j+1]), dp2[j]) + 1;
width = Math.max(dp2[j+1], width);
} else {
dp2[j+1] = 0;
}
}
dp1 = dp2;
}
return width*width;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。