Leetcode(85) Maximal Rectangle

Description

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.

Example:

1
2
3
4
5
6
7
8
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6

解法

我们先从只有一行的矩阵来看。

​ 1 0 1 1 1 0 0 1 1 1 1

如果我们把上面数字都理解成bar的高度,每个bar宽度为1, 那么上面这一行矩阵不就是84题么?!只有一行的矩阵,其实和84题的情况是等价的。换句话说, 84题是退化成一行矩阵情况的85题!

那么, 既然84题是退化成一行的,我们应该有个直觉, 那就是85题可以对每一行执行一次84题的算法, 最终应该能算出最大面积来!

对每一行计算,自然计算出的就是这一行里的最大面积。 要计算全部呢?简单, 如果当前行 j 位仍然是1,那么height[j]++。否则height[j]更新为0,只要矩形无法连续, 那之前的结果也不应参与当前行的计算。

比如上面一行, 经过84题算法, 得出最面积为4. 再来第二行:

​ 1 0 1 1 1 0 0 1 1 1 1

​ 0 1 0 0 1 1 1 1 1 1 1

到第二行的时候, 我们的矩阵其实经过加和变为了: 0 1 0 0 2 1 1 2 2 2 2, 那么通过84题算法可以轻松算出最大面积为8。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix.length == 0) {
return 0;
}
int[] tmp = new int[matrix[0].length];
for (int i = 0; i < matrix[0].length; i++) {
tmp[i] = matrix[0][i] - '0';
}
int res = largestRectangleArea(tmp);
for (int i = 1; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == '0') {
tmp[j] = 0;
} else {
tmp[j] = matrix[i][j] - '0' + tmp[j];
}
}
res = Math.max(res, largestRectangleArea(tmp));
}
return res;
}

int largestRectangleArea(int[] heights) {
int res = 0;
Stack<Integer> s = new Stack();
int[] h = new int[heights.length + 1];
for (int i = 0; i < h.length; i++) {
if (i < heights.length) {
h[i] = heights[i];
} else {
h[i] = 0;
}
}
for (int i = 0; i < h.length; i++) {
if (s.empty() || h[i] > s.peek()) {
s.push(h[i]);
} else {
int count = 0;
while (!s.empty() && s.peek() > h[i]) {
count++;
res = Math.max(res, s.peek() * count);
s.pop();
}
while (count > 0) {
s.push(h[i]);
count--;
}
s.push(h[i]);
}
}
return res;
}
}