[LintCode] Maximal Rectangle 最大矩形

时间:2023-03-08 21:06:18
[LintCode] Maximal Rectangle 最大矩形

Given a 2D boolean matrix filled with False and True, find the largest rectangle containing all True and return its area.

Example
Given a matrix:

[
[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]
]
return 6.

LeetCode上的原题,请参见我之前的博客Maximal Rectangle

解法一:

class Solution {
public:
/**
* @param matrix a boolean 2D matrix
* @return an integer
*/
int maximalRectangle(vector<vector<bool> > &matrix) {
if (matrix.empty() || matrix[].empty()) return ;
int res = , m = matrix.size(), n = matrix[].size();
vector<int> h(n + , );
for (int i = ; i < m; ++i) {
stack<int> s;
for (int j = ; j < n + ; ++j) {
if (j < n) {
if (matrix[i][j]) ++h[j];
else h[j] = ;
}
while (!s.empty() && h[s.top()] >= h[j]) {
int cur = s.top(); s.pop();
res = max(res, h[cur] * (s.empty() ? j : (j - s.top() - )));
}
s.push(j);
}
}
return res;
}
};

解法二:

class Solution {
public:
/**
* @param matrix a boolean 2D matrix
* @return an integer
*/
int maximalRectangle(vector<vector<bool> > &matrix) {
if (matrix.empty() || matrix[].empty()) return ;
int res = , m = matrix.size(), n = matrix[].size();
vector<int> h(n, ), left(n, ), right(n, n);
for (int i = ; i < m; ++i) {
int cur_left = , cur_right = n;
for (int j = ; j < n; ++j) {
h[j] = matrix[i][j] ? h[j] + : ;
}
for (int j = ; j < n; ++j) {
if (matrix[i][j]) left[j] = max(left[j], cur_left);
else {left[j] = ; cur_left = j + ;}
}
for (int j = n - ; j >= ; --j) {
if (matrix[i][j]) right[j] = min(right[j], cur_right);
else {right[j] = n; cur_right = j;}
}
for (int j = ; j < n; ++j) {
res = max(res, (right[j] - left[j]) * h[j]);
}
}
return res;
}
};