求最大子矩阵的大小——C++实现

题目:

       给定一个整型矩阵matrix,其中的值只有0和1两种,求其中全是1的所有矩形区域中,最大的矩阵区域为1的数量。

      例如:

      1  1  1   0

      其中,最大的矩形区域有3个1,所有返回3。

      再如:

     1  0  1  1

     1  1  1  1

     1  1  1  0

     其中,最大的矩形区域有6个1,所以返回6.


解答:

      见代码:

      

class Solution 
{
public:
    int maximalRectangle(vector<vector<int>>& matrix) 
    {
        if(matrix.empty())
        {
            return 0;
        }
        int maxArea = 0;
        vector<int> height(matrix[0].size(), 0);
        for(int i=0; i<matrix.size(); ++i)
        {
            for(int j=0; j<matrix[0].size(); ++j)
            {
                height[j] = (matrix[i][j] == 0) ? 0 : height[j] + 1;
            }
            maxArea = (maxRecFromBottom(height) > maxArea) ? maxRecFromBottom(height) : maxArea;
        }
        return maxArea;
    }
    
    int maxRecFromBottom(vector<int> height)
    {
        if(height.size() == 0)
        {
            return 0;
        }
        int maxArea = 0;
        stack<int> stack1;
        for(int i=0; i<height.size(); ++i)
        {
            while(!stack1.empty() && height[i] <= height[stack1.top()])
            {
                int j = stack1.top();
                stack1.pop();
                int k = stack1.empty() ? -1 : stack1.top();
                int curArea = (i - k - 1) * height[j];
                maxArea = (maxArea > curArea) ? maxArea : curArea;
            }
            stack1.push(i);
        }
        while(!stack1.empty())
        {
            int j = stack1.top();
            stack1.pop();
            int k = stack1.empty() ? -1 : stack1.top();
            int curArea = (height.size() - k - 1) * height[j];
            maxArea = (maxArea > curArea) ? maxArea : curArea;
        }
        return maxArea;
    }
};


如果矩阵的大小为O(N*M),上面代码的时间复杂度为O(N*M),详细解答见左程云著《程序员代码面试指南》。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值