Maximal Square

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

For example, given the following matrix:

``````1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
``````

Return 4.

动态规划

思路

``dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1``

代码

``````public class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix.length == 0) return 0;
int m = matrix.length, n = matrix[0].length;
int max = 0;
int[][] dp = new int[m][n];
// 第一列赋值
for(int i = 0; i < m; i++){
dp[i][0] = matrix[i][0] - '0';
max = Math.max(max, dp[i][0]);
}
// 第一行赋值
for(int i = 0; i < n; i++){
dp[0][i] = matrix[0][i] - '0';
max = Math.max(max, dp[0][i]);
}
// 递推
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
dp[i][j] = matrix[i][j] == '1' ? Math.min(dp[i-1][j-1], Math.min(dp[i-1][j], dp[i][j-1])) + 1 : 0;
max = Math.max(max, dp[i][j]);
}
}
return max * max;
}
}``````

你可能感兴趣的

1 条评论

“当我们判断以某个点为正方形右下角时最大的正方形时，那它的上方，左方和左上方三个点也一定是某个正方形的右下角”这句话怎么理解？？