Leetcode85. 最大矩形
题目:
给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
题解:
解法一:暴力解法
- 我们首先计算出矩阵的每个元素的左边连续 1的数量,使用二维数组 left \textit{left} left 记录,其中 l e f t [ i ] [ j ] left[i][j] left[i][j]为矩阵第 i行第 j列元素的左边连续 1 的数量。
- 随后,对于矩阵中任意一个点,我们枚举以该点为右下角的全 1矩形。
解法二:单调栈
在解法一中,我们讨论了将输入拆分成一系列的柱状图。为了计算矩形的最大面积,我们只需要计算每个柱状图中的最大面积,并找到全局最大值。
我们可以使用Leetcode84. 柱状图中最大的矩形 中的单调栈的做法,将其应用在我们生成的柱状图中。
/**
* @param matrix
* @return
*/
public static int maximalRectangle(char[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] left = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
left[i][j] = (j == 0 ? 0 : left[i][j - 1]) + 1;
}
}
}
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (left[i][j] == 0) {
continue;
}
int width = left[i][j];
int area = width;
for (int k = i - 1; k >= 0; k--) {
width = Math.min(width, left[k][j]);
area = Math.max(area, (i - k + 1) * width);
}
res = Math.max(res, area);
}
}
return res;
}
/**
* 计算每一层的高度
*
* @param matrix
* @return
*/
public static int maximalRectangle2(char[][] matrix) {
if (matrix.length == 0) return 0;
int m = matrix.length;
int n = matrix[0].length;
int[] heights = new int[n];
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
heights[j] += 1;
} else {
heights[j] = 0;
}
}
res = Math.max(res, largestRectangleArea(heights));
}
return res;
}
public static int largestRectangleArea(int[] heights) {
int len = heights.length;
if (len == 0) {
return 0;
}
if (len == 1) {
return heights[0];
}
int[] nums = new int[len + 2];
nums[0] = 0;
nums[len + 1] = 0;
for (int i = 1; i <= len; i++) {
nums[i] = heights[i - 1];
}
Deque<Integer> stack = new ArrayDeque<>(len);
stack.addLast(0);
int res = 0;
for (int i = 1; i < len + 2; i++) {
while (nums[i] < nums[stack.peekLast()]) {
int curHeight = nums[stack.pollLast()];
int curWidth = i - stack.peekLast() - 1;
res = Math.max(res, curHeight * curWidth);
}
stack.addLast(i);
}
return res;
}