LeetCode 85. Maximal Rectangle

Posted co0oder

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 85. Maximal Rectangle相关的知识,希望对你有一定的参考价值。

 1 class Solution {
 2 public:
 3     int maximalRectangle(vector<vector<char>>& matrix) {
 4         /** largest rectangle based solution **/
 5         if(matrix.size()<=0 || matrix[0].size()<=0)
 6             return 0;
 7         int m=matrix.size();
 8         int n=matrix[0].size()+1;
 9         int h=0, w=0, result=0;
10         vector<int> height(n, 0);
11         for(int i=0; i<m; i++){
12             stack<int> s;
13             for(int j=0; j<n; j++){
14                 /** update the current row ended height array **/
15                 if(j<n-1){
16                     if(matrix[i][j]==1)  height[j]+=1;
17                     else height[j]=0;
18                 }
19                 /** use the histogram-max-rectangle-module **/
20                 while(!s.empty() && height[s.top()]>=height[j]){
21                     h=height[s.top()];
22                     s.pop();
23                     w=s.empty() ? j:j-s.top()-1;
24                     if(h*w>result) result=h*w;
25                 }
26                 s.push(j);
27             }
28         }
29         return result;
30     }
31 };

 

 1 class Solution {
 2 public:
 3     int maximalRectangle(vector<vector<char>>& matrix) {
 4         if(matrix.empty()) return 0;
 5         const int m=matrix.size();
 6         const int n=matrix[0].size();
 7         vector<int> left(n,0), right(n,n), height(n,0);
 8         int result=0;
 9         for(int i=0; i<m; i++){
10             int cur_left=0, cur_right=n;
11             for(int j=0; j<n; j++){
12                 if(matrix[i][j]==1) height[j]++;
13                 else height[j]=0;
14             }
15             for(int j=0; j<n; j++){
16                 if(matrix[i][j]==1) left[j]=max(left[j], cur_left);
17                 else  { left[j]=0; cur_left=j+1; }
18             }
19             for(int j=n-1; j>=0; j--){
20                 if(matrix[i][j]==1) right[j]=min(right[j], cur_right);
21                 else  { right[j]=n; cur_right=j; }
22             }
23             for(int j=0; j<n; j++){
24                 result=max(result, (right[j]-left[j])*height[j]);
25             }
26         }
27         return result;
28     }
29 };

留坑

以上是关于LeetCode 85. Maximal Rectangle的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 85. Maximal Rectangle

Leetcode 85. Maximal Rectangle

LeetCode 85: Maximal Recetangle

LeetCode(85) Maximal Rectangle

leetcode 85. Maximal Rectangle

[leetcode]85. Maximal Rectangle 最大矩形