描述
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and
return its area.
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and
return its area.
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
int mymax(int a, int b)
{
return a > b ? a : b;
}
int MaxRectangle(vector<int> input)
{
if (input.size() < 1)
return 0;
int result = 0;
input.push_back(0);
stack<int>s;
for (int i = 0; i < input.size();)
{
if (s.empty() || input[i] > input[s.top()])
s.push(i++);
else
{
int tmp = s.top();
s.pop();
int index = s.empty() ? i : i - s.top() - 1;
result = mymax(result, input[tmp] * index);
}
}
return result;
}
int MaxRectangle(const vector<vector<int>> &input)
{
if (input.size() < 1)
return 0;
vector<int> sum(input[0].size(), 0);
sum = input[0];
int col = input[0].size();
int row = input.size();
for (int i = 1; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (input[i][j] == 0)
sum[j] = 0;
else
sum[j] += input[i][j];
}
}
int maxsum = MaxRectangle(sum);
return maxsum;
}
int main()
{
vector<int> vec1 = { 0, 1, 0, 1, 1 };
vector<int> vec2 = { 0, 1, 0, 1, 1 };
vector<int> vec3 = { 0, 1, 1, 1, 1 };
vector<int> vec4 = { 0, 0, 1, 1, 1 };
vector<vector<int>> input = { vec1, vec2, vec3, vec4 };
int maxsum=MaxRectangle(input);
cout << "MaxRectangle:" << maxsum << endl;
}