Maximal Rectangle

来源:互联网 发布:免费广告录音软件 编辑:程序博客网 时间:2024/05/16 07:10

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


Solution:

class Solution {public:    int maximalRectangle(vector<vector<char>>& matrix) {        int m = matrix.size();        if(!m) return 0;        int n = matrix[0].size();        if(!n) return 0;        vector<int> height(n + 1, 0);        stack<int> st;        int maxArea = 0;        for(int i = 0; i < m; ++i)        {            while(!st.empty()) st.pop();            for(int j = 0; j < n; ++j) height[j] = matrix[i][j] == '0' ? 0 : height[j] + 1;            for(int j = 0; j <= n; ++j)            {                if(st.empty() || height[j] >= height[st.top()]) st.push(j);                else                {                    int temp = st.top();                    st.pop();                    maxArea = max(maxArea, height[temp] * (st.empty() ? j : j - st.top() - 1));                    j--;                }            }        }                return maxArea;    }};


0 0