Maximal Rectangle
很不好想的一道题,参考:http://blog.csdn.net/doc_sgl/article/details/11832965
分为两步:把原矩阵转为直方图,再用largest rectangle求解:http://www.cnblogs.com/573177885qq/p/5537334.html
int largestRectangleArea(vector<int>& heights) {
stack<int> s;
heights.push_back(0);
int result=0;
for(int i=0;i<heights.size();)
{
if(s.empty()||heights[i]>heights[s.top()])
{
s.push(i++);
}
else
{
int tmp=s.top();
s.pop();
result=max(result,heights[tmp]*(s.empty()?i:i-s.top()-1));
}
}
return result;
}
int maximalRectangle(vector<vector<char>>& matrix) {
int m=matrix.size();
int n=matrix[0].size();
if(m==0 || n==0)return 0;
vector<vector<int>>dp(m,vector<int>(n,0));
for(int j=0;j<n;j++)
if(matrix[0][j]=='1')dp[0][j]=1;
for(int j=0;j<n;j++)
{
for(int i=1;i<m;i++)
{
if(matrix[i][j]=='1')dp[i][j]=dp[i-1][j]+1;
}
}
int max_area=0;
for(int i=0;i<m;i++)
max_area=max(max_area,largestRectangleArea(dp[i]));
return max_area;
}