首页 > 代码库 > 【LeetCode】Maximal Rectangle

【LeetCode】Maximal Rectangle

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

 

【LeetCode】Maximal Rectangle