[Leetcode] maximal rectangle 最大矩形

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

题意:求全由1组成的最大矩形面积。

思路:这题感觉是largest rectangle in histogram的变形。对二维矩阵中每一行而言,其向上的部分都可以看成一个直方图,对每一行都调用一下上题的解法。我们可以用一个数组实时更新每个直方图的高度,对于高度的求法:如当前位置上为'0'则,整个高度为0,如为'1',则在该行之前的高度上加1(即,数组本身加1)。参考了Grandyang的博客代码如下:

 1 class Solution {
 2 public:
 3     int maximalRectangle(vector<vector<char> > &matrix) 
 4     {
 5         int row=matrix.size(),col=matrix[0].size();
 6         if(row==0||col==0)  return 0;
 7 
 8         int res=0;
 9         vector<int> height(col,0);
10         for(int i=0;i<row;++i)
11         {
12             for(int j=0;j<col;++j)
13             {
14                 height[j]=matrix[i][j]=='0'?0(1+height[j]);
15             }
16             res=max(res,largestArea(height));
17         }       
18         return res;
19     }
20 
21     int largestArea(vector<int> &height)
22     {
23         int res=0;
24         stack<int> stk;
25         height.push_back(0);
26         for(int i=0;i<height.size();++i)
27         {
28             if(stk.empty()||height[stk.top()]<=height[i])
29                 stk.push(i);
30             else
31             {
32                 int temp=stk.top();
33                 stk.pop();
34                 res=max(res,height[temp]*(stk.empty()?i:(i-stk.top()-1)));
35                 --i;
36             }
37         }
38         return res;
39     }
40 };

 

转载于:https://www.cnblogs.com/love-yh/p/7181924.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值