题目:biubiu
题意:给一个二维矩阵,存的是1和0,求1可以构成的最大矩形。
思维转换,力扣84柱状图的最大矩形的变换。
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
vector<int>l(n), r(n,n);
stack<int>p;
for (int i = 0; i < n; i++) {
while (!p.empty() && heights[p.top()] >= heights[i]) {
r[p.top()] = i;
p.pop();
}
l[i] = p.empty() ? -1 : p.top();
p.push(i);
}
/*while (p.size())
p.pop();
for (int i = n - 1; i >= 0; i--) {
while (!p.empty() && heights[p.top()] >= heights[i])
p.pop();
r[i] = p.empty() ? n : p.top();
p.push(i);
}*/
int ans = 0;
for (int i = 0; i < n; i++) {
ans = max(ans, (r[i] - l[i] - 1) * heights[i]);
}
return ans;
}
int maximalRectangle(vector<vector<char>>& matrix) {
int ans = 0;
if(matrix.size()==0)
return 0;
vector<int>heights(matrix[0].size(),0);
for (const auto& p:matrix) {
for (int i = 0;i<p.size();i++) {
if (p[i] == '1')
heights[i]++;
else
heights[i]=0;
}
/*for(const auto&q:heights){
cout<<q<<" ";
}
cout<<endl;*/
//cout<<largestRectangleArea(heights)<<endl;
ans = max(ans, largestRectangleArea(heights));
}
return ans;
}
};
方法二:
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.size() == 0)
return 0;
vector<vector<int>>widths(matrix.size(), vector<int>(matrix[0].size(),0));
for (int i = 0;i<matrix.size();i++) {
for (int j = 0; j < matrix[i].size(); j++) {
if (matrix[i][j] == '1')
widths[i][j] = (j == 0 ? 1 : widths[i][j - 1] + 1);
}
}
int ans = 0;
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
if (matrix[i][j] == '0')
continue;
int h = j + 2;
for (int k = i; k >= 0; k--) {
h = min(h, widths[k][j]);
ans = max(ans, (i-k + 1)*h);
}
}
}
return ans;
}
};
官方题解思路,先遍历找到每一行的可以形成矩形的长,然后在遍历得到高。