暴力法就不说了,直接讲用动态规划,设dp[i][j]为右下方节点为index[i][j]的最大方块的边长,则:
1.i=0,dp[0][j]=index[0][j];
2.j=0,dp[i][0]=index[i]][0];
3.if index[i][j]=0,dp[i][j]=0,else: dp[i][j]=min(dp[i][j-1],dp[i-1][j],dp[i-1][j-1];
public class Solution {
public int maximalSquare(char[][] matrix) {
int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;
int[][] dp = new int[rows + 1][cols + 1];
int maxsqlen = 0;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
if (matrix[i-1][j-1] == '1'){
dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
maxsqlen = Math.max(maxsqlen, dp[i][j]);
}
}
}
return maxsqlen * maxsqlen;
}
}
pre是在确定dp[j]之后更新,所以dp[j]对应的是index[i][j+1]时的pre,所以在更新dp[j]之前,保存之(tem=dp[j]),更新完之后,更新之(pre=tem)
public class Solution {
public int maximalSquare(char[][] matrix) {
int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;
int[] dp = new int[cols + 1];
int maxsqlen = 0, prev = 0;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
int temp = dp[j];
if (matrix[i - 1][j - 1] == '1') {
dp[j] = Math.min(Math.min(dp[j - 1], prev), dp[j]) + 1;
maxsqlen = Math.max(maxsqlen, dp[j]);
} else {
dp[j] = 0;
}
prev = temp;
}
}
return maxsqlen * maxsqlen;
}
}