Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area
1:特殊情况;
int largestRectangleArea(vector<int> &height)
{
if(height.size() == 0)
{
return 0;
}
int size = (int)height.size();
stack<int> myStack;
int maxValue = 0;
for(int i = 0; i < size; i++)
{
if(myStack.empty() || height[i] >= height[myStack.top()])
{
myStack.push(i);
}
else
{
while(!myStack.empty() && height[i] < height[myStack.top()])
{
int temp = height[myStack.top()];
myStack.pop();
int tempValue = temp * (!myStack.empty() ? i - myStack.top() - 1 : i);
if(tempValue > maxValue)
{
maxValue = tempValue;
}
}
myStack.push(i);
}
}
while(!myStack.empty())
{
int index = myStack.top();
int temp = height[index];
myStack.pop();
int tempValue = temp * (!myStack.empty() ? size - myStack.top() - 1 : size);
if(tempValue > maxValue)
{
maxValue = tempValue;
}
}
return maxValue;
}
int maximalRectangle(vector<vector<char> > &matrix)
{
if(matrix.size() == 0 || matrix[0].size() == 0)
{
return 0;
}
int rows = (int)matrix.size();
int columns = (int)matrix[0].size();
vector<int> height(columns, 0);
int maxValue = 0;
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
if(matrix[i][j] == '0')
{
height[j] = 0;
}
else if(matrix[i][j] == '1')
{
height[j] = height[j] + 1;
}
}
int tempValue = largestRectangleArea(height);
if(tempValue > maxValue)
{
maxValue = tempValue;
}
}
return maxValue;
}