题目:
给定一个整型矩阵matrix,其中的值只有0和1两种,求其中全是1的所有矩形区域中,最大的矩阵区域为1的数量。
例如:
1 1 1 0
其中,最大的矩形区域有3个1,所有返回3。
再如:
1 0 1 1
1 1 1 1
1 1 1 0
其中,最大的矩形区域有6个1,所以返回6.
解答:
见代码:
class Solution
{
public:
int maximalRectangle(vector<vector<int>>& matrix)
{
if(matrix.empty())
{
return 0;
}
int maxArea = 0;
vector<int> height(matrix[0].size(), 0);
for(int i=0; i<matrix.size(); ++i)
{
for(int j=0; j<matrix[0].size(); ++j)
{
height[j] = (matrix[i][j] == 0) ? 0 : height[j] + 1;
}
maxArea = (maxRecFromBottom(height) > maxArea) ? maxRecFromBottom(height) : maxArea;
}
return maxArea;
}
int maxRecFromBottom(vector<int> height)
{
if(height.size() == 0)
{
return 0;
}
int maxArea = 0;
stack<int> stack1;
for(int i=0; i<height.size(); ++i)
{
while(!stack1.empty() && height[i] <= height[stack1.top()])
{
int j = stack1.top();
stack1.pop();
int k = stack1.empty() ? -1 : stack1.top();
int curArea = (i - k - 1) * height[j];
maxArea = (maxArea > curArea) ? maxArea : curArea;
}
stack1.push(i);
}
while(!stack1.empty())
{
int j = stack1.top();
stack1.pop();
int k = stack1.empty() ? -1 : stack1.top();
int curArea = (height.size() - k - 1) * height[j];
maxArea = (maxArea > curArea) ? maxArea : curArea;
}
return maxArea;
}
};
如果矩阵的大小为O(N*M),上面代码的时间复杂度为O(N*M),详细解答见左程云著《程序员代码面试指南》。