ๅฆๆ matrix[i-1][j-1] == 0 ๏ผDP[i, j] ไนๆฏ 0๏ผๅ ็บ square ไธๅญๅจ
ๅฆๆ matrix[i-1][j-1] == 1๏ผ้ฃ้บผ DP[i, j] ๅฐฑๆไปฅไธๅนพ็จฎๅฏ่ฝ
1๏ผๅพDP [i-1,j] ้ๅๅฝข็ ๅ ไธไธ่ก
2๏ผๅพDP [i, j-1] ้ๅๅฝข็ ๅ ไธไธๅ
3๏ผๅพDP [i-1, j-1] ้ๅๆญฃๆนๅฝขๅ ไธไธ่กๅไธๅ
1.ๅญๅ้ก
2. dp function:
ๆๅ่ฝๆฑ็ๅ
ถๅฏฆๆฏ้้ท
dp[i][j]: base on right down corner i,j - the larget side length (ๆณจๆๆฏ้้ท
dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
ๆณจๆ้้ก่ฆๆฑ็ๆฏ้ข็ฉ, ๆไปฅ้้ท*้้ท
/*
time complexity: O(m*n), space complexity: O(m*n), m is matrix's width, n is matrix's height
*/
class Solution {
public int maximalSquare(char[][] matrix) {
int m = matrix.length;
if (m == 0) return 0;
int n = matrix[0].length;
int dp[][] = new int[m+1][n+1];
int maxLen = 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(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
maxLen = Math.max(maxLen, dp[i][j]);
}
}
}
return maxLen*maxLen;
}
}
same idea as 1277. Count Square Submatrices with All Ones
class Solution {
public int maximalSquare(char[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int maxLen = 0;
int dp[][] = new int[m][n];
for (int i = 0; i < m; i++) {
if (matrix[i][0] == '1') {
dp[i][0] = 1;
maxLen = 1;
}
}
for (int i = 1; i < n; i++) {
if (matrix[0][i] == '1') {
dp[0][i] = 1;
maxLen = 1;
}
}
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;
maxLen = Math.max(maxLen, dp[i][j]);
}
}
}
return maxLen*maxLen;
}
}