给你一个二维矩阵,权值为False和True,找到一个最大的矩形,使得里面的值全部为True,输出它的面积
样例:
给你一个矩阵如下
[
[1, 1, 0, 0, 1],
[0, 1, 0, 0, 1],
[0, 0, 1, 1, 1],
[0, 0, 1, 1, 1],
[0, 0, 0, 0, 1]
]
输出6
思路:
参考题目“直方图最大矩形覆盖”,将矩阵的每一行当做是直方图来求解。
#ifndef C510_H
#define C510_H
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
class Solution {
public:
/*
* @param matrix: a boolean 2D matrix
* @return: an integer
*/
int maximalRectangle(vector<vector<bool>> &matrix) {
// write your code here
if (matrix.empty())
return 0;
int row = matrix.size();
int col = matrix[0].size();
vector<vector<int>> v(row, vector<int>(col, 0));
for (int j = 0; j < col; ++j)
{
for (int i = 0; i < row; ++i)
{
if (matrix[i][j])
{
v[i][j] = 1;
if (i>0)
v[i][j] += v[i - 1][j];
}
}
}
int area = 0;
for (auto &c : v)
{
area = maxVal(largestRectangleArea(c), area);
}
return area;
}
int largestRectangleArea(vector<int> &height) {
int res = 0;
stack<int> s;
height.push_back(0);
for (int i = 0; i < height.size(); ++i) {
if (s.empty() || height[s.top()] < height[i]) s.push(i);
else {
int cur = s.top();
s.pop();
res = maxVal(res, height[cur] * (s.empty() ? i : (i - s.top() - 1)));
--i;
}
}
return res;
}
int maxVal(int a, int b)
{
return a > b ? a : b;
}
};
#endif