leetcode No85. Maximal Rectangle

来源:互联网 发布:电力巡检系统java源码 编辑:程序博客网 时间:2024/06/03 16:52

Question

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 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.

Algorithm

类似leetcode No84. Largest Rectangle in Histogram
http://blog.csdn.net/u011391629/article/details/53096334

每遍历一层,更新heights数组的高度

比如
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
每一层每个元素对应的高度为,对应的面积
1 0 1 0 0
2 0 2 1 1
3 1 3 2 2
4 0 0 3 0

Accepted Code

class Solution {public:    int maximalRectangle(vector<vector<char>>& matrix) {        if(matrix.empty())            return 0;        int M = matrix.size();        int N = matrix[0].size();        vector<int> height(N+1, 0);        int res = 0;        int i = 0, j = 0;        for (i = 0; i<M; i++)        {            for (j = 0; j<N; j++)            {                if (matrix[i][j] == '0')                    height[j] = 0;                else                    height[j] += 1;            }            stack<int> s;            int k = 0;            while (k<=N){                if (s.empty() || height[k]>=height[s.top()])                    s.push(k++);                else{                    int curheight = height[s.top()];                    s.pop();                    int curindex = s.empty() ? -1 : s.top();                    res = max(res, curheight*(k - curindex - 1));                }            }        }        return res;    }};
原创粉丝点击