题目地址:
https://www.lintcode.com/problem/the-number-of-0-submatrix/description
给定一个二维 0 − 1 0-1 0−1矩阵,问 0 0 0矩阵的数量。
参考https://blog.csdn.net/qq_46105170/article/details/108935687里的法3单调栈做法即可。代码如下:
import java.util.ArrayDeque;
import java.util.Deque;
public class Solution {
/**
* @param matrix: a matrix
* @return: Number of submatrices that are all 0
*/
public long countSubmatrix(int[][] matrix) {
// write your code here
int m = matrix.length, n = matrix[0].length;
// dp[i][j]存以matrix[i][j]为底向上能延伸多少个0(包括matrix[i][j]自己)
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 1) {
dp[i][j] = 0;
} else {
dp[i][j] = 1;
if (i > 0) {
dp[i][j] += dp[i - 1][j];
}
}
}
}
long res = 0;
for (int i = 0; i < m; i++) {
res += calculate(dp[i]);
}
return res;
}
// 计算以height为柱子高度的柱状图里,以当前行为底的0矩阵的数量
private long calculate(int[] height) {
long count = 0;
Deque<Integer> stack = new ArrayDeque<>();
stack.push(-1);
for (int i = 0; i < height.length; i++) {
while (stack.peek() != -1 && height[stack.peek()] > height[i]) {
int top = stack.pop();
int h = stack.peek() == -1 ? height[top] - height[i] : height[top] - Math.max(height[stack.peek()], height[i]);
int w = i - stack.peek() - 1;
count += h * (w + 1) * w / 2;
}
stack.push(i);
}
while (stack.peek() != -1) {
int top = stack.pop();
int h = stack.peek() == -1 ? height[top] : height[top] - height[stack.peek()];
int w = height.length - stack.peek() - 1;
count += h * (w + 1) * w / 2;
}
return count;
}
}
时空复杂度 O ( m n ) O(mn) O(mn)。