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.


思路:

0 1  0

0 0 1

1 0 1

可以看出这个二维矩阵的返回值是2

可以将这个问题转化成Largest Rectangle in Histogram问题

0 1 0   -->  0 1 0

0 0 1   -->  0 0 1

1 0 1  -->   1 0 2

对于matrix[i][j]

if(matrix[i][j]=='0')

arr[i][j]=0;

else 

arr[i][j]=arr[i-1][j]+1;

后面调用Largest Rectangle in Histogram的函数求解


class Solution {
public:
#define MAX(a,b)  ((a)>=(b))?(a):(b)
    
    int largestRectangleArea(vector<int> &height) {
        if(height.size()<=0)
            return 0;
        else if(height.size()==1)
            return height[0];
        stack<int> stk;
        int ma=0;
        for(int i=0;i<height.size();i++)
        {
            if(stk.empty()||height[i]>=stk.top())
                stk.push(height[i]);
            else if(height[i]<stk.top())
            {
                int count=0;
                while(!stk.empty()&&stk.top()>height[i])
                {
                    ++count;
                    ma=MAX(ma,count*stk.top());
                    stk.pop();
                }
                
                for(int j=0;j<count+1;j++)
                    stk.push(height[i]);
            }
        }
        
        int count=0;
        while(!stk.empty())
        {
            ++count;
            ma=MAX(ma,count*stk.top());
            stk.pop();
        }
        
        return ma;
        
    }
    
    int maximalRectangle(vector<vector<char> > &matrix) {
        int max=0;
        if(matrix.size()<=0)
            return 0;
        
        int **arr=new int*[matrix.size()];
        for(int i=0;i<matrix.size();i++)
        {
            arr[i]=new int[matrix[0].size()];
            memset(arr[i],0,sizeof(int)*matrix[0].size());
        }
        vector<int> temp;
        for(int i=0;i<matrix[0].size();i++){
            arr[0][i]=matrix[0][i]-'0';
            temp.push_back(arr[0][i]);
        }
        max=largestRectangleArea(temp);
        for(int i=1;i<matrix.size();i++)
        {
            vector<int> temp;
            for(int j=0;j<matrix[i].size();j++)
            {
                if(matrix[i][j]=='0')
                    arr[i][j]=0;
                else if(matrix[i][j]=='1')
                    arr[i][j]=arr[i-1][j]+1;
                        
                temp.push_back(arr[i][j]);
            }
            max=MAX(max,largestRectangleArea(temp));
        }
        return max;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值