DP
if matrix[i][j] == '1' dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1;
else dp[i][j] = 0
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0) return 0;
int height = matrix.length;
int width = matrix[0].length;
int[][] dp = new int[height][width];
for (int i = 0; i < height; i++) {
dp[i][0] = (int)(matrix[i][0] - '0');
}
for (int j = 0; j <width; j++) {
dp[0][j] = (int)(matrix[0][j] - '0');
}
for (int i = 1; i < height; i++) {
for (int j = 1; j < width; j++) {
if (matrix[i][j] == '1') {
dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1], dp[i][j - 1]), dp[i - 1][j]) + 1;
} else {
dp[i][j] = 0;
}
}
}
//Find the largest element in dp
int res = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
res = Math.max(res, dp[i][j]);
}
}
return res*res;
}
No comments:
Post a Comment