[LeetCode]Maximal Rectangle
来源:互联网 发布:mill9.1编程文字教程 编辑:程序博客网 时间:2024/05/18 03:00
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
在一个M * N的矩阵中,所有的元素只有0和1, 找出只包含1的最大矩形。
例如:图中是一个4 × 6的矩形,画出红色的是我们要找到的区域。
仔细观察发现:因为我们要找的是矩形,所以它一定是以 某个行元素开始的,这样的话,其实我们要找到的某个矩形就转换成 一某一个行开始的 histogram的最大矩形问题了。
那么我们原始矩形可以变成如下的形式的数据:
第一行表示,我们以第一行作为底边,所形成的 histogram的高度,其他行也类似。所以问题变成了 枚举每一行,然后求出每一行对应的histogram的最大矩形。histogram参考:
class Solution {public: int maximalRectangle(vector<vector<char>>& matrix) { int col = matrix.size(); if(col==0) return 0; int row = matrix[0].size(); int res = 0; for(int j=0; j<row; ++j){ int flag = 0; for(int i=0; i<col; ++i){ if(matrix[i][j]=='1'){ flag++; matrix[i][j]='0'+flag; } else if(matrix[i][j]=='0'){ flag = 0; } } } for(int i=0; i<col; ++i){ int temp = largestRectangleArea(matrix[i]); res = res>temp?res:temp; } return res; } int largestRectangleArea(vector<char>& height) { stack<int> index; stack<char> h; if(height.size()==0) return 0; index.push(0); h.push(height[0]); int area = 0; for(int i=1; i<height.size(); ++i){ if(h.empty()||height[i]>h.top()){ index.push(i); h.push(height[i]); } else if(height[i]<h.top()){ int tempIdx = 0; while(!h.empty() && height[i]<=h.top()){ tempIdx = index.top(); area = area>(i-index.top())*(h.top()-'0')?area:(i-index.top())*(h.top()-'0'); h.pop(); index.pop(); } index.push(tempIdx); h.push(height[i]); } } while(!h.empty()){ area = area >(height.size()-index.top())*(h.top()-'0')? area:(height.size()-index.top())*(h.top()-'0'); h.pop(); index.pop(); } return area; }};
0 0
- 【LeetCode】Maximal Rectangle && Maximal Square
- Leetcode:Maximal Square & Maximal Rectangle
- LeetCode: Maximal Rectangle
- LeetCode Maximal Rectangle
- LeetCode: Maximal Rectangle
- [LeetCode] Maximal Rectangle
- [leetcode] Maximal Rectangle
- [LeetCode]Maximal Rectangle
- [leetcode]Maximal Rectangle
- LeetCode-Maximal Rectangle
- [leetcode] Maximal Rectangle
- Leetcode Maximal Rectangle
- [LeetCode] Maximal Rectangle
- leetcode Maximal Rectangle
- LeetCode Maximal Rectangle
- LeetCode | Maximal Rectangle
- [LeetCode] Maximal Rectangle
- [Leetcode] Maximal Rectangle (Java)
- 《算法竞赛入门经典2ndEdition 》习题3-9 子序列(All in All, Uva10340)
- Python中数字以及算数运算符的相关使用
- android - Adding Custom Suggestions
- IE与Firefox在JavaScript上的7个不同句法
- 硬盘的基本结构
- [LeetCode]Maximal Rectangle
- leetcode -- Maximum Product Subarray -- 重点
- android5.0无法使用HttpClient解决办法
- 《用Python玩转数据》Week5, Part 2
- FatFs读写SD卡出现FR_NO_FILESYSTEM解决方法.
- 2015年科技巨头的十个开源产品,不只是.NET、Swift
- cocos2d-x学习笔记(10)重复动作RepeatForever和Repeat 以及动作组合Sequence和Spawn
- iOS基础之OC:C与OC的对比,(NSString,NSLog)
- [LeetCode]Largest Rectangle in Histogram