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

/**
* This problem can be simply converted to "Largest Rectangle in Histogram" problem,
* for each rows, calcuate the height in each columns than solve it.
*
* Since we could solve "Largest Rectangle in Histogram" in O(n), the run time for this
* question is just O(m) * (O(n) + O(n)), in which m is total rows and, first m is
* for calculating heights, and second n is for cacualte reactangle area. In total
* it's O(mn);
*/
#include <vector> #include <iostream> #include <stack> using namespace std; int largestRectangleArea(vector<int> &height) { int size = height.size(); vector<int> width(size); stack<int> limit; // find left-most reachable bar for (int i = 0; i < size; ++i) { int left = 0; while (!limit.empty()) { if (height[limit.top()] < height[i]) { left = limit.top()+1; break; } else { limit.pop(); } } width[i] = left; limit.push(i); } limit = stack<int>(); for (int i = size-1; i >= 0; --i) { int right = size-1; while(!limit.empty()) { if (height[limit.top()] < height[i]) { right = limit.top()-1; break; } else { limit.pop(); } } width[i] = right-width[i]+1; limit.push(i); } int maxArea = 0; for (int i = 0; i < size; ++i) { int area = height[i]*width[i]; if (maxArea < area) { maxArea = area; } } return maxArea; } int maximalRectangle(vector<vector<char> > &matrix) { int rows = matrix.size(); if (rows == 0) return 0; int cols = matrix[0].size(); vector<int> heights(cols); int maxArea = 0; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (matrix[i][j] == '0') { heights[j] = 0; } else { heights[j] +=1; } } int area = largestRectangleArea(heights); if (maxArea < area) { maxArea = area; } } return maxArea; }
View Program Text


Test Status