Given a 2D boolean
matrix filled with False
and True
, find the largest rectangle containing all True
and return its area.
Example
参考 http://blog.csdn.net/qq_31552435/article/details/51839175
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
.
class Solution {
public:
/**
* @param matrix a boolean 2D matrix
* @return an integer
*/
int maximalRectangle(vector<vector<bool> > &matrix) {
// Write your code here
int res = 0;
if (matrix.empty()) {
return res;
}
const int m = matrix.size();
const int n = matrix[0].size();
vector<int> temp (n, 0);
vector<vector<int>> dp(m, temp);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && matrix[i][j]) {
dp[i][j] = 1;
continue;
}
if (matrix[i][j]) {
dp[i][j] = dp[i - 1][j] + 1;
}
}
}
for (int i = 0; i < m; i++) {
res = max(res, largestRectangleArea(dp[i]));
}
return res;
}
int largestRectangleArea(vector<int> &height) {
// write your code here
// write your code here
stack<int> S;
height.push_back(0);
int sum = 0;
for (int i = 0; i < height.size(); i++) {
if (S.empty() || height[i] > height[S.top()]) S.push(i);
else {
int tmp = S.top();
S.pop();
sum = max(sum, height[tmp]*(S.empty()? i : i-S.top()-1));
i--; //拿着右边界, 寻找左边界;!!!!!
}
}
return sum;
}
};