与えられた m * n
ものと0の行列、何を返す の正方形 部分行列は、すべてのものを持っています。
例1:
Input: matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is 1 square of side 3.
Total number of squares = 10 + 4 + 1 = 15.
アイデア:DPを入力座標、全ての第1のinitは、次に漸化式は、1です。
A [i]は[J] == 1、DP [I-1] [j]は、DP [I]、[J-1]、DP [I-1] [J-1]が0であり、そしてその後最小を取ることができません値は、
DP [I] [J] + =分(DP [I-1] [j]は、DP [I]、[J-1]、DP [I-1] [J-1])。
T:O(N * M)S:O(N * M)。
class Solution {
public int countSquares(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int n = matrix.length;
int m = matrix[0].length;
int[][] dp = new int[n][m];
// initial;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
dp[i][j] = matrix[i][j];
}
}
// calculate matrix;
int count = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(i >= 1 && j >= 1) {
if(dp[i][j] == 1) {
if(dp[i-1][j] != 0 && dp[i][j-1] != 0 && dp[i-1][j-1] != 0) {
dp[i][j] += Math.min(dp[i-1][j],
Math.min(dp[i][j-1], dp[i-1][j-1]));
}
}
}
count += dp[i][j];
}
}
return count;
}
}
Aは、その配列をすることができ、変更した場合、面接であなたは、あなたが直接modifyA配列、スペースはO(1)に還元することができることができた場合、尋ねます。
class Solution {
public int countSquares(int[][] A) {
if(A == null || A.length == 0 || A[0].length == 0) {
return 0;
}
int n = A.length;
int m = A[0].length;
int count = 0;
// calculate matrix;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(i >= 1 && j >= 1) {
if(A[i][j] == 1) {
if(A[i-1][j] != 0 && A[i][j-1] != 0 && A[i-1][j-1] != 0) {
A[i][j] = Math.min(A[i-1][j],
Math.min(A[i][j-1], A[i-1][j-1])) + 1;
}
}
}
count += A[i][j];
}
}
return count;
}
}