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 中一次扫描并利用stack的方法
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
int rows = matrix.size();
if (rows == 0)
return 0;
int columns = matrix[0].size();
if (columns == 0)
return 0;
vector<int> heights(columns);
stack<int> tmpStack;
int maxArea = INT_MIN;
for (int i=0; i<rows; i++)
{
stack<int>().swap(tmpStack);
for (int j=0; j<columns; j++)
{
if (matrix[i][j] == '1')
{
if (i>0 && matrix[i-1][j] == '1')
heights[j]++;
else
heights[j] = 1;
}
else
{
heights[j] = 0;
}
}
for (int j=0; j<columns;)
{
if (tmpStack.size() == 0 || heights[j] >= heights[tmpStack.top()])
{
tmpStack.push(j++);
}
else
{
int curHeight = heights[tmpStack.top()];
tmpStack.pop();
maxArea = max(maxArea, curHeight * (tmpStack.empty()? j: j-tmpStack.top()-1));
}
}
while (!tmpStack.empty())
{
int curHeight = heights[tmpStack.top()];
tmpStack.pop();
maxArea = max(maxArea, curHeight * (tmpStack.empty()? columns: columns-tmpStack.top()-1));
}
}
return maxArea;
}
};