问题描述:
给定一个矩阵,该矩阵中的元素只包含1和0,找出该矩阵中全为1的矩形面积的最大值。
如:
1 1 0 0 0
1 0 0 0 1
1 0 0 0 1
对应的矩形面积的最大值为3。
整体思路:
通过求解每列中到当前行的连续1的个数,然后将该题转化为求解柱状图最大面积问题。
举个栗子:
1 1 0 1 0
1 0 1 1 1
1 0 1 0 1
计算每列中到当前行的连续1的个数得到:
1 1 0 1 0
2 0 1 2 1
3 0 2 0 2
把得到的矩阵的每一行看成一个柱状图,求每个柱状图可形成的最大面积,最终求最大,即为全为1的矩形面积的最大值。
其它步骤比较简单,问题的关键就变成了柱状图可形成的最大面积的求解。柱状图可形成的最大面积问题详见这里。
C++代码
// An highlighted block
#include <iostream>
#include <ctime>
#include <stack>
using namespace std;
//求矩阵中最大的全为1的矩形的面积
int MaxSquareArea(int* s, int m, int n);
int BarsMaxArea(int* gHeights, int nItem);
struct cell
{
int h;
int w;
cell(int height):h(height), w(1){}
};
int main()
{
int m=5;
int n=6;
int* s=new int[m*n];
unsigned seed = time(0);
srand(seed);
for(int i=0;i<m;++i)
{
for(int j=0;j<n;++j)
{
s[i*n+j]=rand()%2;
cout<<s[i*n+j]<<" ";
}
cout<<endl;
}
cout<<endl;
cout<<MaxSquareArea(s, m, n)<<endl;
delete[] s;
return 0;
}
int MaxSquareArea(int* s, int m, int n)
{
//计算每一列中到当前行的连续1的个数
for(int j=0;j<n;++j)
{
for(int i=1;i<m;++i)
{
if(s[i*n+j]>0)
s[i*n+j]=s[(i-1)*n+j]+1;
}
}
int Vmax = 0;
for(int i=0;i<m;++i)
{
int* data = new int[n];
for(int k=0;k<n;++k)
data[k] = s[i*n+k];
// Vmax=max(Vmax,(int)BarsMaxArea1(data, n));
Vmax=max(Vmax,BarsMaxArea(data, n));
delete[] data;
}
return Vmax;
}
//计算柱状图最大面积
int BarsMaxArea(int* gHeights, int nItem)
{
int i;
stack<Node> s;
long long height;
s.push(Node(-1, 0));//将最小高度加入堆栈,防止堆栈弹空
int currentPosition;
long long maxArea = 0;//记录最大面积
long long curArea;
for( i = 0; i <= nItem ; i++)
{
currentPosition = i + 1;//获得当前 位置
if( i == nItem)//这时候,我们认为到达最后,我们要弹空栈
{
height = 0;
}
else
{
height = gHeights[currentPosition-1];
}
Node t(height, currentPosition);//当前节点
while( s.top().height > height)
{
cout<<s.top().height<<" "<<height<<endl;
t = s.top();
s.pop();
curArea = (currentPosition - t.startIdx) * t.height;//按照某个高度的 开始和结束的位置,获得面积
if(curArea > maxArea)
{
maxArea = curArea;
}
}
s.push(Node(height, t.startIdx));
}
return maxArea;
}