-
Notifications
You must be signed in to change notification settings - Fork 0
/
0085.最大矩形.cpp
93 lines (89 loc) · 2.15 KB
/
0085.最大矩形.cpp
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* @lc app=leetcode.cn id=85 lang=cpp
*
* [85] 最大矩形
*
* https://leetcode-cn.com/problems/maximal-rectangle/description/
*
* algorithms
* Hard (43.65%)
* Likes: 253
* Dislikes: 0
* Total Accepted: 13.4K
* Total Submissions: 31.1K
* Testcase Example: '[["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]'
*
* 给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
*
* 示例:
*
* 输入:
* [
* ["1","0","1","0","0"],
* ["1","0","1","1","1"],
* ["1","1","1","1","1"],
* ["1","0","0","1","0"]
* ]
* 输出: 6
*
*/
// @lc code=start
#include <stack>
#include <vector>
using namespace std;
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix)
{
if (matrix.size() == 0) {
return 0;
}
int tmp = 0;
int ans = 0;
vector<int> height(matrix[0].size(), 0);
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[0].size(); ++j) {
if (matrix[i][j] == '1') {
++height[j];
} else {
height[j] = 0;
}
}
tmp = area(height);
if (tmp > ans) {
ans = tmp;
}
}
return ans;
}
int area(vector<int> height)
{
stack<int> pos;
pos.push(-1);
int p = 0;
int h = 0;
int tmp = 0;
int ans = 0;
for (p = 0; p < height.size(); ++p) {
while (pos.top() != -1 && height[p] < height[pos.top()]) {
h = height[pos.top()];
pos.pop();
tmp = (p - pos.top() - 1) * h;
if (tmp > ans) {
ans = tmp;
}
}
pos.push(p);
}
while (pos.top() != -1) {
h = height[pos.top()];
pos.pop();
tmp = (height.size() - pos.top() - 1) * h;
if (tmp > ans) {
ans = tmp;
}
}
return ans;
}
};
// @lc code=end