1. 程式人生 > >[Leetcode] maximal rectangle 最大矩形

[Leetcode] maximal rectangle 最大矩形

with ++ leetcode 當前 push_back ont 更新 tor tco

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

[Leetcode] maximal rectangle 最大矩形