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

【LeetCode】Maximal Rectangle

时间:2014-12-06 16:44:58      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   strong   

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.

 

如果用DP来做,判断(begin1,end1)~(begin2,end2)范围是否全1,会超时。

 

对于矩阵matrix,逐行构建height数组,调用Largest Rectangle in Histogram即可。

对matrix第i行构建height数组方法:对于height[j],即从matrix[i][j]开始,最多到达matrix[0][j]的连续1个数。

class Solution {
public:
    int maximalRectangle(vector<vector<char> > &matrix) {
        if(matrix.empty())
            return 0;
        int result = 0;
        int row = matrix.size();
        int col = matrix[0].size();
        for(int i = 0; i < row; i ++)
        {//for ith vector, reduct into "Largest Rectangle in Histogram"
            vector<int> height(col, 0);
            for(int j = 0; j < col; j ++)
            {
                int ind = i;
                while(ind >= 0 && matrix[ind][j] == 1)
                {
                    ind --;
                    height[j] ++;
                }
            }
            result = max(result, largestRectangleArea(height));
        }
        return result;
    }
    
    int largestRectangleArea(vector<int> &height) {
        if(height.empty())
            return 0;
            
        int result = 0;
        stack<int> s;   //elements in stack s are kept in ascending order
        int ind = 0;
        while(ind < height.size())
        {
            if(s.empty() || height[ind]>=s.top())
            {
                s.push(height[ind]);
            }
            else
            {
                int count = 0;  //pop count
                while(!s.empty() && height[ind]<s.top())
                {
                    int top = s.top();
                    s.pop();
                    count ++;
                    result = max(result, count*top);
                }
                for(int i = 0; i <= count; i ++)
                    s.push(height[ind]);    //push count+1 times
            }
            ind ++;
        }
        //all elements are in stack s, and in ascending order
        int count = 0;
        while(!s.empty())
        {
            count ++;
            int top = s.top();
            s.pop();
            result = max(result, count*top);
        }
        
        return result;
    }
};

bubuko.com,布布扣

 

【LeetCode】Maximal Rectangle

标签:style   blog   http   io   ar   color   sp   for   strong   

原文地址:http://www.cnblogs.com/ganganloveu/p/4148350.html

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