[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 };

 

posted @ 2017-07-15 16:12  王大咩的图书馆  阅读(245)  评论(0编辑  收藏  举报