LeetCode85 Maximal Rectangle 解题报告

本文介绍了一种解决二维矩阵中寻找由1组成的最大矩形面积问题的方法。通过扩展LeetCode第84题的思路,利用栈来遍历并计算矩阵中每一行的高度,最终找出最大面积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 6.

题目的意思是给一个二维矩阵,求出这个二维矩阵1所能组成的最大的长方形面积

思路:思路是根据84的思路进行求解,只不过加入多一个for循环,用来更新heights数组,当所在的元素(matrix[i][j])为0的时候,heights[j]设置为0, 当为1的时候,即对heights[j]++,然后根据84题的思路使用stack 遍历改height数组进行求解。这里稍微优化下,是每次对height[j]进行判断的时候,直接加入维护的stack中,效果是一样的。

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) 
    {
        if(matrix.size()==0)
        {
            return 0;
        }
        int re=0;
        int row=matrix.size();
        int col=matrix[0].size();

        stack<int> s;
        vector<int> height(col+1,0);
        int count=0;
        for(int i=0;i<row;i++)
        {
            for(int j=0;j<=col;j++)
            {
                if(j<col)
                {
                    if(matrix[i][j]=='1')
                    {
                        height[j]++;
                    }
                    else
                    {
                        height[j]=0;
                    }
                }
                if(s.empty()||s.top()<=height[j])
                {
                    s.push(height[j]);
                }
                else if(s.top()>height[j])
                {
                    count=0;
                    while(s.empty()==false&&s.top()>height[j])
                    {
                        count++;
                        re=max(re,count*s.top());
                        s.pop();
                    }
                    for(int k=0;k<=count;k++)
                    {
                        s.push(height[j]);
                    }
                }
            }
            while(s.empty()==false)
            {
                count++;
                re=max(re,count*s.top());
                s.pop();
            }
        }

        return re;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值