leetcode64:maximal-rectangle

题目描述

给出一个只包含0和1的二维矩阵,找出最大的全部元素都是1的长方形区域,返回该区域的面积。

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
class Solution {
public:
    int maximalRectangle(vector<vector<char> > &matrix) {
        if (matrix.size()==0)
            return 0;
        int m=matrix.size();
        int n=matrix[0].size();
        vector< int> h(n);
        int maxS=0;
        int num;
        stack<int> st;
        st.push(-1);
        for (int i=0;i<m;i++)
        {
            for (int j=0;j<n;j++){
                if (matrix[i][j]=='1')
                    h[j]++;
                else
                    h[j]=0;
                
            }
            
            for (int j=0;j<n;j++){
                while (st.top()!=-1 && h[j] <h[st.top()])
                {
                    num=st.top();
                    st.pop();
                    maxS=max(maxS,(j-1-st.top())*h[num]);
                    
                }
                st.push(j);
            }
            while (st.top()!=-1){
                num=st.top();
                st.pop();
                maxS=max(maxS,(n-1-st.top())*h[num]);
            }
        }
        return maxS;
    }
};
posted on 2020-08-03 18:45  滚雪球效应  阅读(63)  评论(0编辑  收藏  举报