原题如下:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
此题是在上篇博文的基础上的进一步深入,具体思路参考这篇博文中的第二种方法:http://www.cnblogs.com/lichen782/p/leetcode_maximal_rectangle.html,因为在前述博文中http://blog.youkuaiyun.com/momentforver/article/details/27653621我们已经求出了针对柱状图的最大面积的求法,所以在此题中,可以把矩阵当前行以上的连续1的个数作为柱状图的高度,这样,针对每行可以首先求出行节点的高度并用一个向量来存储高度值,然后利用上题中的思路求解当前行以上的最大面积,当遍历完所有行时,最大面积即可求出。
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
int m = matrix.size();
if(m == 0)
return 0;
int n = matrix[0].size();
if(n == 0)
return 0;
vector<int>height(n,0);
int maxArea = 0;
for(int i = 0; i < m; i++){
for(int j =0; j < n; j++){
if(matrix[i][j] == '0')
height[j] = 0;
else
{
height[j] = height[j] + 1;
}
}
maxArea = max(maxArea,largestArea(height));
}
return maxArea;
}
int largestArea(vector<int>height){
height.push_back(0);
int len = height.size();
int i = 0;
int maxArea = 0;
stack<int>s; //存储下标
s.push(0);
while (i < len)
{
if(s.empty() || height[s.top()] <= height[i]){
s.push(i++);
}
else{
int t = s.top();
s.pop();
maxArea = max(maxArea,height[t] * (s.empty() ? i: i - 1 - s.top()));
}
}
return maxArea;
}
};
从代码可以看出,int largestArea 就是上篇博文中我们所采用的方法。