力扣 题目85- 最大矩形

题目

题解

一看这不是和力扣 题目84- 柱状图中最大的矩形差不多吗 那么我们以行 为一个柱状图 然后传入84题的过程不就可以了

例如第一行是 10100 而第二行是20211 即+1操作

特殊情况是0 如果有0的话那么当前柱子就会被截断

例如第四行 应该是4 0 0 3 0

1                 if (matrix[i][j] == '1') {
2                     heights[j] += 1;
3                 }
4                 else {
5                     heights[j] = 0;
6                 }

代码

 1 #include<iostream>
 2 #include<vector>
 3 #include<stack>
 4 using namespace std;
 5 class Solution {
 6 public:
 7     int maximalRectangle(vector<vector<char>>& matrix) {
 8         Solution sol;
 9         int area = 0;
10         vector<int>heights(matrix[0].size(),0 );
11         for (int i = 0; i < matrix.size(); i++) {
12             for (int j = 0; j < matrix[i].size(); j++) {
13                 if (matrix[i][j] == '1') {
14                     heights[j] += 1;
15                 }
16                 else {
17                     heights[j] = 0;
18                 }
19             }
20             area = max(sol.largestRectangleArea(heights), area);
21             //由于在84题 运算中加入了两个柱子帮助运算 所以这里要删除
22             heights.pop_back();
23             heights.erase(heights.begin());
24         }
25         return area;
26     }
27 
28     int largestRectangleArea(vector<int>& heights) {
29         heights.insert(heights.begin(), 0);
30         heights.push_back(0);
31         stack<int> stack;
32         int area = 0;
33         for (int i = 0; i < heights.size(); i++) {
34             while (stack.size() != 0 && heights[i] < heights[stack.top()]) {
35                 int h = heights[stack.top()];
36                 stack.pop();
37                 area = max(area, (i - stack.top() - 1) * h);
38             }
39             stack.push(i);
40         }
41         return area;
42     }
43 };
44 
45 int main() {
46     Solution sol;
47     vector<vector<char>> matrix = { {'1','0','1','0','0'} ,{'1','0','1','1','1'},{'1','1','1','1','1'},{'1','0','0','1','0'} };
48     int result = sol.maximalRectangle(matrix);
49     cout << result << endl;
50 }
View Code

 

posted @ 2022-07-08 17:11  无聊的阿库娅  阅读(31)  评论(0编辑  收藏  举报