-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaximal Rectangle.cpp
54 lines (45 loc) · 1.55 KB
/
Maximal Rectangle.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
// https://oj.leetcode.com/problems/maximal-rectangle/
// Find "1" height for each slot, then harness the solution to largest rectangle area
// to find the maximum area.
class Solution {
// Refer to: https://oj.leetcode.com/problems/largest-rectangle-in-histogram/
int largestRectangleArea(vector<int> &height) {
if (height.size() == 0) {
return 0;
}
int max_area = 0;
stack<int> stk;
height.push_back(0);
for (int i = 0; i < height.size(); ) {
if (stk.empty() || height[i] > height[stk.top()]) {
stk.push(i++);
} else {
int last = stk.top();
stk.pop();
int wid = stk.empty() ? i : i - stk.top() - 1;
int area = wid * height[last];
max_area = max(max_area, area);
}
}
return max_area;
}
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if (matrix.size() == 0) {
return 0;
}
int R = matrix.size();
int C = matrix[0].size();
vector<int> heights(C, 0);
// find largest area containing all 1s
int max_area = 0;
for (int i = 0; i < R; ++i) {
for (int j = 0; j < C; ++j) {
heights[j] = (matrix[i][j] == '1') ? heights[j] + 1 : 0;
}
int area = largestRectangleArea(heights);
max_area = max(max_area, area);
}
return max_area;
}
};