【LeetCode】85. Maximal Rectangle
Maximal Rectangle
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
如果用DP来做,判断(begin1,end1)~(begin2,end2)范围是否全1,会超时。
对于矩阵matrix,逐行构建height数组,调用Largest Rectangle in Histogram即可。
对matrix第i行构建height数组方法:对于height[j],即从matrix[i][j]开始,最多到达matrix[0][j]的连续1个数。
class Solution { public: int maximalRectangle(vector<vector<char> > &matrix) { int ret = 0;; if(matrix.empty() || matrix[0].empty()) return ret; int m = matrix.size(); int n = matrix[0].size(); for(int i = 0; i < matrix.size(); i ++) { vector<int> height(n, 0); for(int j = 0; j < n; j ++) { int r = i; while(r >= 0 && matrix[r][j] == '1') { height[j] ++; r --; } } ret = max(ret, largestRectangleArea(height)); } return ret; } int largestRectangleArea(vector<int> &height) { if(height.empty()) return 0; int result = 0; stack<int> s; //elements in stack s are kept in ascending order int ind = 0; while(ind < height.size()) { if(s.empty() || height[ind]>=s.top()) { s.push(height[ind]); } else { int count = 0; //pop count while(!s.empty() && height[ind]<s.top()) { int top = s.top(); s.pop(); count ++; result = max(result, count*top); } for(int i = 0; i <= count; i ++) s.push(height[ind]); //push count+1 times } ind ++; } //all elements are in stack s, and in ascending order int count = 0; while(!s.empty()) { count ++; int top = s.top(); s.pop(); result = max(result, count*top); } return result; } };