求最大子矩阵的大小
(题目)
给定一个整型矩阵map,其中的值只有0和1两种,求其中全是1的所有矩形区域中,
(题目)
给定一个整型矩阵map,其中的值只有0和1两种,求其中全是1的所有矩形区域中,
最大的矩形区域为1的数量。
例如:
1 1 1 0
其中,最大的矩形区域有3个1,所以返回3。
再如:
1 0 1 1
例如:
1 1 1 0
其中,最大的矩形区域有3个1,所以返回3。
再如:
1 0 1 1
1 1 1 1
1 1 1 0
其中,最大的矩形区域有6个1,所以返回6。
#include<iostream>
#include<stdio.h>
#include<stack>
using namespace std;
template<class T>
int length(T& arr)
{
return sizeof(arr) / sizeof(arr[0]);
}
int maxRecFromBottom(int myheight[], int x)
{
int height[5];
for(int i = 0; i < x; i++)
{
height[i] = myheight[i];
}
int mylength = length(height);
if(mylength == 0)
{
return 0;
}
int maxArea = 0;
stack<int> s1;
for(int i = 0; i < mylength; i++)
{
while(!s1.empty() && height[i] <= height[s1.top()])
{
//下标为i的数想要挑战单调栈栈顶
int cur1 = s1.top();//单调栈栈顶的值(当前待处理值)
s1.pop();
int cur2 = s1.empty() ? -1 : s1.top();//当前待处理值的下一个值
int curArea = (i - cur2 - 1) * height[cur1];
maxArea = curArea > maxArea ? curArea : maxArea;
}
s1.push(i);
}
while(!s1.empty())
{
int j = s1.top();
s1.pop();
int k = s1.empty() ? -1 : s1.top();
int curArea = (mylength - k - 1) * height[j];
maxArea = curArea > maxArea ? curArea : maxArea;
}
return maxArea;
}
int maxRecSize(int mymap[][4], int x, int y)
{
int maxArea = 0;
int height[y] = {0};
for(int i = 0; i < x; i++)
{
for(int j = 0; j < y; j++)
{
cout<< height[j]<<" ";
height[j] = mymap[i][j] == 0 ? 0 : height[j] + 1;
}
cout<<endl;
maxArea = maxRecFromBottom(height, y) > maxArea ? maxRecFromBottom(height, y) : maxArea;
}
return maxArea;
}
int main()
{
//1011
//1111
//1110
int x;
cin>>x;
int myans[x][4];
for(int i = 0; i < x; i++)
{
for(int j = 0; j < 4; j++)
{
cin>>myans[i][j];
}
}
int ans = maxRecSize(myans, x, 4);
cout<<ans;
return 0;
}