[LeetCode] Maximal Rectangle(good)

时间:2023-03-08 17:43:49

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

参考“Largest Rectangle in Histogram”这个题的解法,思想差不多一样,只是用h向量表示Rectangle中此元素中第一行到本行的高度,非常妙的算法:

class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if(matrix.size() == || matrix[].size() == )
return ;
int cLen = matrix[].size();
int rLen = matrix.size();
//height array
vector<int> h(cLen+,); int max = ; for(int row = ;row<rLen;row++){//for(1)
stack<int> s;
for(int i=;i<cLen+;i++){//for(2)
if(i<cLen){
if(matrix[row][i]=='')
h[i] += ;
else
h[i] = ;
}//end if if(s.empty() || h[s.top()]<=h[i]){
s.push(i);
}else{
while(!s.empty() && h[i]<h[s.top()]){
int top = s.top();
s.pop();
int area = h[top]*(s.empty()?i:(i-s.top()-));
if(area > max)
max = area;
}//end while
s.push(i);
}//end if
}//end for(2)
}//end for(1)
return max;
}//end func
};