Maximal Rectangle

来源:互联网 发布:sqoop导入数据到hbase 编辑:程序博客网 时间:2024/06/03 14:19

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

有了上一题的基础,这题就不在话下了。

举个例子:

0 0 1 1

1 1 0 1

0 1 1 0

1 1 1 1 

上面的例子,在你去找全由1组成的矩形的时候,会发现,可以看做是由1在纵向上组成的矩形最大面积是多少,也就可以化成:

0 0 1 1

1 1 0 2

0 2 1 0

1 3 2 1

然后对每一行做上述寻找最大容量的问题。

class Solution {public:    int Max(int a, int b){return a > b ? a : b;}    int largestRectangleArea(vector<int> &height) {    height.push_back(0);        stack<int> stk;        int i = 0;        int maxArea = 0;        while(i < height.size()){            if(stk.empty() || height[stk.top()] <= height[i]){                stk.push(i++);            }else {                int t = stk.top();stk.pop();                maxArea = Max(maxArea, height[t] * (stk.empty() ? i : i - stk.top() - 1));            }        }        return maxArea;    }        int maximalRectangle(vector<vector<char> > &matrix) {        int m = matrix.size();        if(m==0) return 0;        int n = matrix[0].size();                vector<vector<int> > area(m,vector<int>(n,0));        for(int i = 0;i < m;i++)            for(int j = 0;j < n;j++)                if(i == 0)                    area[i][j] = matrix[i][j] - '0';                else                    area[i][j] = (matrix[i][j]=='1')?area[i-1][j]+1:0;                            int res = 0;        for(int k = 0;k<m;k++)            res = Max(largestRectangleArea(area[k]),res);        return res;    }};


0 0
原创粉丝点击