码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Maximal Rectangle(good)

时间:2014-08-15 12:45:58      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   div   amp   

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

参考“Largest Rectangle in Histogram”这个题的解法,思想差不多一样,只是用h向量表示Rectangle中此元素中第一行到本行的高度,非常妙的算法:

class Solution {
public:
    int maximalRectangle(vector<vector<char> > &matrix) {
        if(matrix.size() == 0 || matrix[0].size() == 0)
            return 0;
        int cLen = matrix[0].size();
        int rLen = matrix.size();
        //height array
        vector<int> h(cLen+1,0);
    
        int max = 0;

        for(int row = 0;row<rLen;row++){//for(1)
           stack<int> s;
           for(int i=0;i<cLen+1;i++){//for(2)
               if(i<cLen){
                  if(matrix[row][i]==1)
                      h[i] += 1;
                  else
                      h[i] = 0;
               }//end if

               if(s.empty() || h[s.top()]<=h[i]){
                   s.push(i);
               }else{
                   while(!s.empty() && h[i]<h[s.top()]){
                      int top = s.top();
                      s.pop();
                      int area = h[top]*(s.empty()?i:(i-s.top()-1));
                      if(area > max)
                          max = area;
                   }//end while
                   s.push(i);
               }//end if
           }//end for(2)        
        }//end for(1)
        return max;
    }//end func
};

 

[LeetCode] Maximal Rectangle(good),布布扣,bubuko.com

[LeetCode] Maximal Rectangle(good)

标签:style   blog   color   io   for   ar   div   amp   

原文地址:http://www.cnblogs.com/Xylophone/p/3914469.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!