首页 > 代码库 > 【LeetCode】Maximal Rectangle
【LeetCode】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) { if(matrix.empty()) return 0; int result = 0; int row = matrix.size(); int col = matrix[0].size(); for(int i = 0; i < row; i ++) {//for ith vector, reduct into "Largest Rectangle in Histogram" vector<int> height(col, 0); for(int j = 0; j < col; j ++) { int ind = i; while(ind >= 0 && matrix[ind][j] == ‘1‘) { ind --; height[j] ++; } } result = max(result, largestRectangleArea(height)); } return result; } 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; }};
【LeetCode】Maximal Rectangle
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。