dp function的含义比较特别,dp[i][j] stands for the max square side length whose lower right corner is matrix[i][j].
转换方程也很棒,以matrix[i][j]为右下角的正方形边长是以matrix[i - 1][j], matrix[i][j - 1], matrix[i - 1][j - 1]最小值加一,搞清楚这个关键点问题就很简单了。
class Solution {
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0){
return 0;
}
int m = matrix.length;
int n = matrix[0].length;
//dp[i][j] representing max square side length whose lower-right corner is matrix[i][j]
int[][] dp = new int[m][n];
int max = 0;
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++){
if (matrix[i][j] == '1'){
dp[i][j] = Math.min(dp[i - 1][j], Math.min(dp[i][j - 1], dp[i - 1][j - 1])) + 1;
} else {
dp[i][j] = 0;
}
max = Math.max(max, dp[i][j]);
}
}
return max*max;
}
}
网友评论