85. 最大矩形

给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例:

输入:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
输出: 6

思路:对矩阵的每一行做高度统计,把每一行当做直方图并保存在矩阵中,求所有直方图中最大矩形面积(84. 柱状图中最大的矩形,通过栈来确定每个直方图中比当前进栈后循环下标小的下标i,通过计算当前下标i之前所有面积来得出最大面积)

class Solution {
public:
     int getRtgarea(vector height)
    {
        stack st;
        height.push_back(0);
        int area=0;
        for(int i=0;i         {
            while(!st.empty()&&height[st.top()]>=height[i])
            {
                int cur=st.top();
                st.pop();
                area=max(area,height[cur]*(st.empty()?i:(i-st.top()-1)));
            }
            st.push(i);
        }
        return area;
    }
    int maximalRectangle(vector>& matrix) {
        if(matrix.size()==0||matrix[0].size()==0)
            return 0;
        vector> reg;
        for(int i=0;i         {
            vector temp;
            for(int j=0;j             {
                int hei=0;
                for(int k=i;k>=0;k--)
                {
                    if(matrix[k][j]=='0')
                        break;
                    hei++;
                }
                temp.push_back(hei);
            }
            reg.push_back(temp);
        }
        
        int maxrtgarea=0;
        for(int i=0;i         {
            int rtgarea=getRtgarea(reg[i]);
            if(rtgarea>maxrtgarea)
                maxrtgarea=rtgarea;
        }
        return maxrtgarea;
    }
    
   
};

你可能感兴趣的:(85. 最大矩形)