leetcode_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

解析:
方法一、暴力法
遍历整个矩阵,对于每一个1,将其当做矩形的一角,向右下两个方向尝试扩展。

方法二
观察矩阵的一行,发现可以将其代入上一题的代码中,从而获得这一行的最大矩形。

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        int n = matrix.size();
        if(n==0) return 0;
        int m = matrix[0].size();
        if(m==0) return 0;
        vector<int> h(m,0);
        int res = 0;
        for(int i=0;i<n;++i){
            for(int j=0;j<m;++j){
                if(matrix[i][j]=='1') ++h[j];
                else h[j]=0;
            }
            res = max(res,largestRectangleArea(h));
        }
        return res;
    }
    
    int largestRectangleArea(vector<int>& heights) {
        stack<int> st;
        int res = 0;
        int p = 0;
        while(p!=heights.size()){
            if(st.empty()) st.push(p++);
            else{
                if(heights[p]>=heights[st.top()]) st.push(p++);
                else{
                    int h = heights[st.top()];
                    st.pop();
                    res = max(res,(p-(st.empty()?-1:st.top())-1)*h);
                }
            }
        }
        while(!st.empty()){
            int h = heights[st.top()];
            st.pop();
            res = max(res, (int)((heights.size()-(st.empty()?-1:st.top())-1)*h) );
        }
        return res;
    }
    
};
发布了112 篇原创文章 · 获赞 0 · 访问量 366

猜你喜欢

转载自blog.csdn.net/qq_37292201/article/details/103891075
今日推荐