您的位置:首页 > 编程语言 > C语言/C++

* leetcode #85 in cpp

2016-06-12 03:43 483 查看
Solution: 

This question is hard. I did not know how to solve this until I looked up the solution online. Basically to solve this question we employ techniques in #84. That is, we treat this problem as looking for largest rectangle in histogram. 

Example:

given 

011
111
101
We treat each row as the x-axis, and the 1s as the height of the histogram.  
For row 1:  it is [0, 1,1], max rectangle in this histogram is 2.

For row 2: it is [1,2,2], max rect in this histogram is 4; 

For row 3: it is [2,0,3], max rect in this histogram is 3;

Thus we first need to transform the matrix into histograms based on each row(step1), then we use #84 to find out the max rect in the histograms. 

Code:

class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.empty()) return 0;
int m = matrix.size();
int n = matrix[0].size();
vector<vector<int>> hist(m, vector<int>(n,0));
<span style="white-space:pre"> </span>// step 1
for(int i = 0; i < m; i ++){
for(int j = 0; j < n; j ++){
if(matrix[i][j] == '1'){
if(i-1>=0) hist[i][j] = hist[i-1][j] + 1;
else hist[i][j] = 1;
}
}
}
<span style="white-space:pre"> </span>
int max_area = 0;
for(int i = 0; i < m; i ++){
max_area = max(max_area,largestRectangleArea(hist[i]));
}
return max_area;
}
int largestRectangleArea(vector<int>& heights) {
heights.push_back(0);
stack<int> left_ind;
int max_area = 0;
int i = 0;
while(i < heights.size()){
if(left_ind.empty()) {
left_ind.push(i);
i++;
}
else{
if(heights[i] > heights[left_ind.top()]){
left_ind.push(i);
i++;
}else{
int left = left_ind.top();
left_ind.pop();
max_area = max(max_area, heights[left] *(left_ind.empty()? i :(i - left_ind.top() - 1)));
}
}

}
return max_area;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode