Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
思路:
0 1 0
0 0 1
1 0 1
可以看出这个二维矩阵的返回值是2
可以将这个问题转化成Largest Rectangle in Histogram问题
0 1 0 --> 0 1 0
0 0 1 --> 0 0 1
1 0 1 --> 1 0 2
对于matrix[i][j]
if(matrix[i][j]=='0')
arr[i][j]=0;
else
arr[i][j]=arr[i-1][j]+1;
后面调用Largest Rectangle in Histogram的函数求解
class Solution {
public:
#define MAX(a,b) ((a)>=(b))?(a):(b)
int largestRectangleArea(vector<int> &height) {
if(height.size()<=0)
return 0;
else if(height.size()==1)
return height[0];
stack<int> stk;
int ma=0;
for(int i=0;i<height.size();i++)
{
if(stk.empty()||height[i]>=stk.top())
stk.push(height[i]);
else if(height[i]<stk.top())
{
int count=0;
while(!stk.empty()&&stk.top()>height[i])
{
++count;
ma=MAX(ma,count*stk.top());
stk.pop();
}
for(int j=0;j<count+1;j++)
stk.push(height[i]);
}
}
int count=0;
while(!stk.empty())
{
++count;
ma=MAX(ma,count*stk.top());
stk.pop();
}
return ma;
}
int maximalRectangle(vector<vector<char> > &matrix) {
int max=0;
if(matrix.size()<=0)
return 0;
int **arr=new int*[matrix.size()];
for(int i=0;i<matrix.size();i++)
{
arr[i]=new int[matrix[0].size()];
memset(arr[i],0,sizeof(int)*matrix[0].size());
}
vector<int> temp;
for(int i=0;i<matrix[0].size();i++){
arr[0][i]=matrix[0][i]-'0';
temp.push_back(arr[0][i]);
}
max=largestRectangleArea(temp);
for(int i=1;i<matrix.size();i++)
{
vector<int> temp;
for(int j=0;j<matrix[i].size();j++)
{
if(matrix[i][j]=='0')
arr[i][j]=0;
else if(matrix[i][j]=='1')
arr[i][j]=arr[i-1][j]+1;
temp.push_back(arr[i][j]);
}
max=MAX(max,largestRectangleArea(temp));
}
return max;
}
};