O(m*n*worst(m)) = O(m^2n)
如果今天只是1d array...
1 → 1. 中間斷掉了 所以只能算一個
class Solution {
public int numSubmat(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 0) {
continue;
}
// cal left
mat[i][j] = (j == 0 ? 0 : mat[i][j-1]) + 1;
count += mat[i][j];
// cal up
int min = mat[i][j];
for (int k = i-1; k >= 0; k--) {
min = Math.min(min, mat[k][j]);
count += min;
}
}
}
return count;
}
}
/*
O(m*n*worst(m))
*/
class Solution:
def numSubmat(self, mat: List[List[int]]) -> int:
count = 0
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j] == 0:
continue
mat[i][j] = (0 if (j == 0) else mat[i][j-1]) + 1
count += mat[i][j]
min_val = mat[i][j]
for k in range(i-1, -1, -1):
min_val = min(min_val, mat[k][j])
count += min_val
return count