给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximal-rectangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Stack;
class Solution {
private int solve(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
int ret = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < height.length; ++i) {
while (!stack.isEmpty() && height[stack.peek()] >= height[i]) {
Integer pop = stack.pop();
ret = Math.max(ret, height[pop] * (i - (stack.isEmpty() ? -1 : stack.peek()) - 1));
}
stack.push(i);
}
while (!stack.isEmpty()) {
Integer pop = stack.pop();
ret = Math.max(ret, height[pop] * (height.length - (stack.isEmpty() ? -1 : stack.peek()) - 1));
}
return ret;
}
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int ret = 0;
int[] height = new int[matrix[0].length];
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix[0].length; ++j) {
if (matrix[i][j] == '1') {
height[j] += 1;
} else {
height[j] = 0;
}
}
ret = Math.max(ret, solve(height));
}
return ret;
}
}