Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.
DP的过程还没有想清楚,先利用上一题的结果可以解决该问题。统计每一行为止向上有多少个连续的1做为bar的高度,对每一行调用Largest Rectangle in Histogram即可。
代码如下,运行时间32ms:
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.size() == 0 || matrix[0].size() == 0)
return 0;
int row(matrix.size()), col(matrix[0].size()), result(0);
vector<vector<int>> heights(row, vector<int>(col));
for(int i = 0; i < col; ++i)
heights[0][i] = matrix[0][i] - '0';
result = largestRectangleArea(heights[0]);
for(int i = 1; i < row; ++i) {
for(int j = 0; j < col; ++j) {
heights[i][j] = (matrix[i][j] - '0') ? heights[i-1][j] + 1 : 0;
}
int temp(largestRectangleArea(heights[i]));
result = result > temp ? result : temp;
}
return result;
}
int largestRectangleArea(vector<int>& height) {
if(height.size() == 0)
return 0;
//put a minimum number to calculate the area of last rectangle
height.push_back(0);
stack<int> h;
int result(0), index(0), top(0);
while(index < height.size()) {
if(h.empty() || height[h.top()] < height[index]) {
h.push(index++);
}
else {
top = h.top();
h.pop();
//if stack had only 1 element, use index as width, else use current top index to calculate width
top = h.empty() ? height[top] * index : height[top] * (index - h.top() - 1);
result = result > top ? result : top;
}
}
height.pop_back();
return result;
}
};