leetcode 221 maximal square

Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.

For example, given the following matrix:

1
2
3
4
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 4.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class  {
public int maximalSquare(char[][] matrix) {
if(matrix.length == 0) return 0;
if(matrix[0].length == 0) return 0;
int m = matrix.length;
int n = matrix[0].length;

int[][] dp = new int[m+1][n+1];
int size = 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(dp[i-1][j-1], Math.min(dp[i-1][j], dp[i][j-1])) + 1;
size = Math.max(size, dp[i][j]);
}
}
}
return size*size;
}
}
  • dp[i][j] = min(dp[i-1][j-1], dp[j-1][i], dp[i][j-1]) + 1 if(matrix[i-1][j-1] == 1)
  • 这里dp记录的是边长,只有当前点的左边,上边和左上角一般大时,当前点的值才加一
1 (dp = 1) 1 (dp = 1) 0 (dp = 0)
0 (dp = 0) 1 (dp = 1) 1 (dp = 1)
0 (dp = 0) 1 (dp = 1) 1 (dp = 2)
  • 要注意的是,如果最后一个位置的值为0的话,dp = 0 ,因此需要一个变量来保存整个过程中的最大值