[LeetCode]85. Maximal Rectangle

本文详细解析了LeetCode上第85题“最大矩形”的算法实现,采用类似直方图的方法处理二维矩阵,通过逐行构建高度数组并计算最大矩形面积,最终找到矩阵中全为1的最大矩形区域。

[LeetCode]85. Maximal Rectangle

题目描述

这里写图片描述

思路

直方图做法
将每一行看做一个直方图
如例子中的
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
之后类似于直方图的做法,对每一行处理,同时维护一个最大值即可
直方图做法参考另一篇
[LeetCode]84. Largest Rectangle in Histogram

代码

#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if (matrix.size() == 0)
            return 0;
        int row = matrix.size(),
            col = matrix[0].size(),
            res = 0;
        vector<int> h(col, 0);
        for (int i = 0; i < row; ++i) {
            stack<int> s;
            int count = 0;
            for (int j = 0; j < col; ++j) {
                if (matrix[i][j] == '1')
                    ++h[j];
                else 
                    h[j] = 0;
                if (s.empty() || s.top() <= h[j]) {
                    s.push(h[j]);
                }
                else {
                    while (s.size() && s.top() >= h[j]) {
                        ++count;
                        res = max(res, count * s.top());
                        s.pop();
                    }
                    while (count) {
                        s.push(h[j]);
                        --count;
                    }
                    s.push(h[j]);
                }
            }
            while (s.size()) {
                ++count;
                res = max(res, s.top() * count);
                s.pop();
            }
        }
        return res;
    }
};

int main() {
    vector<vector<char>> matrix = {{'1', '0'}};
    Solution s;
    cout << s.maximalRectangle(matrix) << endl;

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值