85. Maximal Rectangle 最大矩形

给定一个仅包含 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;    
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值