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

[leetcode]

时间:2015-01-08 22:47:03      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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 思想类似,只是对每行都执行了一遍。

代码:

int maximalRectangle(vector<vector<char> > &matrix) {  //C++
        if(matrix.size() == 0|| matrix[0].size()==0)
            return 0;
        
        int rows = matrix.size();
        int cols = matrix[0].size();
        
        vector<int> H(cols+1);
        H[cols] = 0;
        int max = 0;
        
        for(int i = 0; i < rows; i++)
        {
            for(int j=0; j<cols; j++)
                if(matrix[i][j]=='1')
                    H[j]++;
                else H[j]=0;
            
            vector<int> stack;
            for(int j = 0; j<cols+1; j++)
            {
                 while(stack.size() >0&&H[stack.back()]>H[j])
                {
                    int h = H[stack.back()];
                    stack.pop_back();
                    
                    int left = stack.size()>0?stack.back():-1;
                    if(h*(j-1-left)>max)
                        max = h*(j-1-left);
                }
                stack.push_back(j);
            }
        }
        return max;
    }


[leetcode]

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/42535173

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