1. 题目
给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例 1:
输入:matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”]
,[“1”,“0”,“0”,“1”,“0”]]
输出:6
解释:最大矩形如上图所示。
示例 2:
输入:matrix = []
输出:0
示例 3:
输入:matrix = [[“0”]]
输出:0
示例 4:
输入:matrix = [[“1”]]
输出:1
示例 5:
输入:matrix = [[“0”,“0”]]
输出:0
提示:
rows == matrix.length
cols == matrix[0].length
0 <= row, cols <= 200
matrix[i][j] 为 ‘0’ 或 ‘1’
Related Topics 栈 数组 哈希表 动态规划
👍 862 👎 0
2. 题解
2.1 解法1: 单调栈
参考 84 题的单调栈解法, 相当于对每一行进行单调栈求解
class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int rowLen = matrix.length;
int colLen = matrix[0].length;
int[] heights = new int[colLen + 2];
int ans = 0;
for (int row = 0; row < rowLen; row++) {
// 计算 heights 数组值
for (int col = 0; col < colLen; col++) {
if (matrix[row][col] == '1') {
heights[col + 1]++;
} else {
heights[col + 1] = 0;
}
}
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < heights.length; i++) {
while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) {
int top = stack.pop();
int left = stack.peek();
ans = Math.max(ans, (i - left - 1) * heights[top]);
}
stack.push(i);
}
}
return ans;
}
}
另一种写法:
class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix.length == 0) {
return 0;
}
int ans = 0;
int row = matrix.length;
int col = matrix[0].length;
int[] heights = new int[col + 1];
for (int i = 0; i < row; i++) {
Deque<Integer> stack = new ArrayDeque<>();
// 计算 heights
for (int j = 0; j < col; j++) {
if (matrix[i][j] == '1') {
heights[j]++;
} else {
heights[j] = 0;
}
}
for (int j = 0; j < heights.length; j++) {
while (!stack.isEmpty() && heights[j] < heights[stack.peek()]) {
int top = stack.pop();
int left = stack.isEmpty() ? -1 : stack.peek();
ans = Math.max(ans, heights[top] * (j - left - 1));
}
stack.push(j);
}
}
return ans;
}
}
参考: 详细通俗的思路分析,多解法