LeetCode 算法 85 最大矩形
题目
给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
解法 单调栈
转化为84题直方图矩形的最大面积
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int m = matrix.size();
if(m == 0)
return 0;
int n = matrix[0].size();
vector<int> heights(n, 0);
int res = 0;
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; j++){
if(matrix[i][j] == '1'){
heights[j]++;
}
else{
heights[j] = 0;
}
}
res = max(res, largestRectangleArea(heights));
}
return res;
}
int largestRectangleArea(vector<int>& heights) {
int m = heights.size();
vector<int> left(m,0);
vector<int> right(m, 0);
int index;
stack<int> s1;
for(int i = 0; i < m; ++i){
while(!s1.empty() && heights[i] < heights[s1.top()]){
index = s1.top();
s1.pop();
right[index] = i;
}
s1.push(i);
}
while(!s1.empty()){
right[s1.top()] = m;
s1.pop();
}
stack<int> s2;
for(int i = m - 1; i >= 0; --i){
while(!s2.empty() && heights[i] < heights[s2.top()]){
index = s2.top();
s2.pop();
left[index] = i;
}
s2.push(i);
}
while(!s2.empty()){
left[s2.top()] = -1;
s2.pop();
}
int ans = 0;
for(int i = 0; i < m; ++i){
ans = max((right[i] - left[i] - 1) * heights[i], ans);
}
return ans;
}
};