【Leetcode】85.最大矩形C++(柱状图法)

在这里插入图片描述

在这里插入图片描述

#include "iostream"

#include "vector"

#include "stack"

using namespace std;

class Solution
{
public:
    int maximalRectangle(vector<vector<char>> &matrix)
    {
        int max_y = matrix.size();
        if (max_y == 0)
        {
            return 0;
        }
        int max_x = matrix[0].size();
        int width, max = 0, tmp;
        vector<int> w(max_y, 0);
        for (int j = 0; j < max_x; j++)
        {
            for (int i = 0; i < max_y; i++)
            {
                if (matrix[i][j] == '1')
                {
                    w[i] = j == 0 ? 1 : w[i] + 1;
                    width = w[i];
                    for (int k = i; k >= 0; k--)
                    {
                        width = width < w[k] ? width : w[k];
                        tmp = width * (i - k + 1);
                        max = max > tmp ? max : tmp;
                    }
                }
                else
                {
                    w[i] = 0;
                }
            }
        }
        return max;
    }
};

int main(int argc, char const *argv[])
{
    int y, x;
    cin >> y;
    cin >> x;
    char c;

    vector<vector<char>> matrix(y, vector<char>(x));

    for(int i=0;i<y;i++)
    {
        for(int j=0;j<x;j++)
        {
            cin >> c;
            matrix[i][j] = c;
        }
    }

    Solution so;
    cout << so.maximalRectangle(matrix);

    return 0;
}

发布了103 篇原创文章 · 获赞 128 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104098252
今日推荐