LeetCode85. Maximal Rectangle
原题地址
题目描述
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
思路
本题借用了LeetCode 84 Largest Rectangle in Histogram中的代码。
将矩阵的每一行看出一个直方图,逐行求出其最大矩阵进行比较。
图片转自 http://blog.youkuaiyun.com/doc_sgl/article/details/11832965
代码实现
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> index;
heights.push_back(0);
int res=0;
for(int i=0;i<heights.size();++i){
if( index.empty() || heights[i]>heights[index.top()]) index.push(i);
else{
int cur=index.top();
index.pop();
res=max(res,heights[cur]*(index.empty()?i:(i-index.top()-1)));
--i;
}
}
return res;
}
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.size()<=0 || matrix[0].size()<=0) return 0;
int row = matrix.size();
int col = matrix[0].size();
vector<vector<int>> heights(row, vector<int>(col));
int maxArea = 0;
for(int i=0; i<row; i++){
for(int j=0; j<col; j++) {
if (matrix[i][j]=='1'){
heights[i][j] = (i==0 ? 1 : heights[i-1][j] + 1);
}
} //构造每个0~i行构成的sub矩阵的直方图输入数据。
maxArea = max(maxArea, largestRectangleArea(heights[i]));
}
return maxArea;
}
};
代码转自: http://blog.youkuaiyun.com/feliciafay/article/details/42293691
鸡汤
放长假心情有些浮躁,没刷题,这一题也看了很多题解才弄懂。还是要坚持一题一题的做,学的东西太多,继续加油,晚安。