85. Maximal Rectangle

来源:互联网 发布:淘宝商家怎么上传商品 编辑:程序博客网 时间:2024/05/23 02:07

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

For example, given the following matrix:

1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 6.


给出一个二维矩阵,找出矩阵中最大的矩形的面积。如果用84题的结果,很容易实现。84题中是求直方图中最大的矩形面积。对矩阵的每一行,都有一个直方图。比如给出的例子的第3行,相当于直方图“2 1 2 2 2”。然后对每一行用84题的算法,算出当前行的直方图的最大矩形面积。然后求出所有行的最大值即可。


代码:

class Solution{public:int maximalRectangle(vector<vector<char> >& matrix) {int m = matrix.size();if(m == 0) return 0;int n = matrix[0].size();if(n == 0) return 0;int res = 0;vector<int>heights(n, 0);for(int i = 0; i < m; ++i){for(int j = 0; j < n; ++j){heights[j] = (matrix[i][j] == '0' ? 0 : heights[j] + 1);}vector<int>tmp = heights;res = max(res, largestRectangleArea(tmp));}return res;}private:int largestRectangleArea(vector<int>& heights) {int n = heights.size();stack<int>stk;int res = 0, top = 0, pre;heights.push_back(0);for(int i = 0; i <= n; ++i){if(!stk.empty()) top = stk.top();pre = i;while(!stk.empty() && heights[i] < heights[stk.top()]){res = max(res, ((heights[stk.top()] ) * (top - stk.top() + 1)));pre = stk.top();stk.pop();}heights[pre] = heights[i];if(pre != i) stk.push(pre);stk.push(i);}return res;}};



0 0
原创粉丝点击