cpp
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int m=matrix.size();
int n=matrix[0].size();
vector<vector<int>> left(m, vector<int>(n,0));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(matrix[i][j] =='1')
left[i][j] = (j>=1?left[i][j-1]:0)+1;
}
}
int area=0;
int w,h;
w=h=0;
int res=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(left[i][j]){
w=left[i][j];
for(int k=i;k>=0;k--){
h=i-k+1;
w=min(w, left[k][j]);
res=max(res, w*h);
}
}
}
}
return res;
}
};
方法二:
求矩阵面积最大的就是用单调栈(公共模版),固定宽度,让高度尽可能大。
cpp
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int m=matrix.size();
int n=matrix[0].size();
vector<vector<int>> left(m, vector<int>(n,0));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(matrix[i][j] =='1')
left[i][j] = (j>=1?left[i][j-1]:0)+1;
}
}
int area, w,h;
area=0;
for(int j=0;j<n;j++){
vector<int> up(m,0);
vector<int> down(m,0);
stack<int> stk;
for(int i=0;i<m;i++){
while(stk.size()&&left[stk.top()][j]>=left[i][j])
stk.pop();
up[i]=(stk.size()==0?-1:stk.top());
stk.push(i);
}
stk=stack<int>();
for(int i=m-1;i>=0;i--){
while(stk.size()&&left[stk.top()][j]>=left[i][j])
stk.pop();
down[i] = (stk.size()==0?m:stk.top());
stk.push(i);
}
for(int i=0;i<m;i++){
int height=down[i]-up[i]-1;
int width=left[i][j];
area = max(area, height*width);
}
}
return area;
}
};