题目描述
给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

C++
class Solution {
public:
/*
动态规划
对每一行利用单调栈的思路+84. 柱状图中最大的矩形,求解,
height[i][j]表示第i行中以第j列的柱子高度为高可以形成的最大面积
*/
int maximalRectangle(vector<vector<char>>& matrix) {
int row=matrix.size();
if( !row) return 0;
int col=matrix[0].size();
vector<vector<int>> height(row+1,vector<int>(col+1));
int res=0;
//初始化,第一行的柱子高度
for(int i=0;i<col;i++){
if(matrix[0][i]=='1'){
height[0][i]=1;
}
}
//填表 ,每一行的柱子高度表
for(int i=1;i<row;i++)
for(int j=0;j<col;j++){
if(matrix[i][j]=='1') height[i][j]=1+height[i-1][j];
}
//对每一行开始用单调栈求柱子的最大面积
for(int i=0;i<row;i++){
stack<int> sta;
vector<int> temp=height[i];
temp.insert(temp.begin(), 0);
temp.push_back(0);
for(int j=0;j<temp.size();j++)
{
while(!sta.empty() &&temp[sta.top()]>temp[j]){
int cur=sta.top();
sta.pop();
int top=sta.top();
res=max(res,temp[cur]*(j-top-1));
}
sta.push(j);
}
}
return res;
}
};
和这道题相关:84. 柱状图中最大的矩形
该博客介绍了如何使用动态规划和单调栈解决找到二进制矩阵中只包含1的最大矩形的问题。通过分析给定的C++代码,可以看到算法首先初始化矩阵的高度,然后逐行计算并利用单调栈找到每行中可以形成的最大面积。最终,返回所有矩形中的最大面积。
625

被折叠的 条评论
为什么被折叠?



