85. Maximal Rectangle (Graph; Stack, DP)

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

 

思路:

例如

01101

11010

01110

11110

11111

00000

按列从上到下计算maximal rectangle:

01101

12010

03110

14210

25321

00000

然后对每一行求直方图的最大面积,于是这个问题可以转化为Largest Rectangle in Histogram。

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        if(height.size() == 0) return 0;
         
        int res = 0;
        stack<int> idxStack;
        height.push_back(0); //为了如果在最后height为最高的情况,能够再进一次else,把stack中的元素pop出来计算
       
        for(int i = 0; i < height.size(); i++)
        {
            if(idxStack.empty() || (!idxStack.empty() && height[i] >= height[idxStack.top()])) //当前高度>=栈顶高度
                idxStack.push(i); //入栈
            else{ //高度降低了,那么再之后也就不可能超过height[idx],所以看之前的高度*宽度能够达到怎样的值
                while(!idxStack.empty() && height[idxStack.top()] > height[i]) //只要当前高度<栈顶高度
                {
                    int idx = idxStack.top(); 
                    idxStack.pop();
                    int width = idxStack.empty() ? i : (i-idxStack.top()-1); //当前index-1的位置(目前为止最高高度的位置)到当前栈顶元素的位置的宽度
                    res = max(res, height[idx] * width);
                }
                idxStack.push(i);
            }
        }
        height.pop_back();
        return res;
    }
    
    int maximalRectangle(vector<vector<char> > &matrix) {
        if (matrix.size() < 1) return 0;
        int n = matrix.size();
        if (n == 0) return 0;
        int m = matrix[0].size();
        if (m == 0) return 0;
        vector<vector<int> > lines(n, vector<int>(m, 0));
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (i == 0) {
                    lines[i][j] = ((matrix[i][j] == '1') ? 1 : 0);
                } else {
                    lines[i][j] += ((matrix[i][j] == '1') ? lines[i-1][j] + 1 : 0);
                }
            }
        }
        int maxRec = 0, tmpRec;
        for (int i = 0; i < n; ++i) {
            tmpRec = largestRectangleArea(lines[i]);
            maxRec = (maxRec > tmpRec) ? maxRec : tmpRec;
        }
        return maxRec;
    }
};

 

posted on 2015-10-08 16:15  joannae  阅读(244)  评论(0编辑  收藏  举报

导航