Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
题目的意思是给一个二维矩阵,求出这个二维矩阵1所能组成的最大的长方形面积
思路:思路是根据84的思路进行求解,只不过加入多一个for循环,用来更新heights数组,当所在的元素(matrix[i][j])为0的时候,heights[j]设置为0, 当为1的时候,即对heights[j]++,然后根据84题的思路使用stack 遍历改height数组进行求解。这里稍微优化下,是每次对height[j]进行判断的时候,直接加入维护的stack中,效果是一样的。
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix)
{
if(matrix.size()==0)
{
return 0;
}
int re=0;
int row=matrix.size();
int col=matrix[0].size();
stack<int> s;
vector<int> height(col+1,0);
int count=0;
for(int i=0;i<row;i++)
{
for(int j=0;j<=col;j++)
{
if(j<col)
{
if(matrix[i][j]=='1')
{
height[j]++;
}
else
{
height[j]=0;
}
}
if(s.empty()||s.top()<=height[j])
{
s.push(height[j]);
}
else if(s.top()>height[j])
{
count=0;
while(s.empty()==false&&s.top()>height[j])
{
count++;
re=max(re,count*s.top());
s.pop();
}
for(int k=0;k<=count;k++)
{
s.push(height[j]);
}
}
}
while(s.empty()==false)
{
count++;
re=max(re,count*s.top());
s.pop();
}
}
return re;
}
};
本文介绍了一种解决二维矩阵中寻找由1组成的最大矩形面积问题的方法。通过扩展LeetCode第84题的思路,利用栈来遍历并计算矩阵中每一行的高度,最终找出最大面积。
339

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



