给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
输出: 6
思想:和Largest Rectangle in Histogram思想类似,举如下例子说明:
假设这是初始化矩阵:
1 1 0 1 0 1
0 1 0 0 1 1
1 1 1 1 0 1
1 1 1 1 0 1
定义一个宽度为列长的数组tmp,对于第一行,初始化为第一行的值,[1 1 0 1 0 1],计算最长的矩形面积为2
对于第二行,更新tmp数组,更新规则为如果matrix对应的第二行元素为1,那么tmp[col]++,否则置为0。那么第二行更新完tmp数组为[0,2,0,0,1,2],最长的矩形面积为2,以此类推。
参考代码:
class Solution {
public:
int maximalRectangle(vector<int> &heights){
stack<int> s;
int res=0;
for(int i=0;i<heights.size();i++){
if(s.empty()) {
s.push(i);
continue;
}
int count=0;
while(!s.empty() && heights[s.top()]>heights[i]){
count++;
res=max(res,count*heights[s.top()]);
s.pop();
}
while(count){
s.push(i);
count--;
}
s.push(i);
}
int count=1;
while(!s.empty()){
res=max(res,count*heights[s.top()]);
s.pop();
count++;
}
return res;
}
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.empty() || matrix[0].empty() || matrix[0].size()==0) return 0;
int res=0;
vector<int> tmp(matrix[0].size(),0);
for(int i=0;i<matrix.size();i++){
for(int j=0;j<matrix[i].size();j++){
tmp[j]=(matrix[i][j]=='1'?tmp[j]+1:0);
}
res=max(res,maximalRectangle(tmp));
}
return res;
}
};