[LeetCode] 01矩阵中最大矩形 Maximal Rectangle
来源:互联网 发布:淘宝历史比价网 编辑:程序博客网 时间:2024/05/22 15:16
相关问题1:[LeetCode] Find max subsquare whose border values are all 1
相关问题2:[LeetCode] 01矩阵中最大正方形 Maximal Square
在一个M * N的矩阵中,所有的元素只有0和1, 找出只包含1的最大矩形。
例如:图中是一个4 × 6的矩形,画出红色的是我们要找到的区域。
仔细观察发现:因为我们要找的是矩形,所以它一定是以 某个行元素开始的,这样的话,其实我们要找到的某个矩形就转换成 一某一个行开始的 histogram的最大矩形问题了。
那么我们原始矩形可以变成如下的形式的数据:
第一行表示,我们以第一行作为底边,所形成的 histogram的高度,其他行也类似。所以问题变成了 枚举每一行,然后求出每一行对应的histogram的最大矩形。利用单调栈求histogram的最大矩形可以参考:http://blog.csdn.net/jiyanfeng1/article/details/8067265
代码如下:
int maximalRectangle(vector<vector<char> > &matrix) { // max rectangle in a 0-1 matrix if(matrix.size()==0) return 0; int* hist = new int[matrix[0].size()]; memset(hist, 0, sizeof(int)*matrix[0].size()); int max_ = 0; for(int i=0; i<matrix.size(); i++) { for(int j=0; j<matrix[0].size(); j++) { if(matrix[i][j]=='1') *(hist+j) += 1; else *(hist+j) = 0; } max_ = max(max_, maxRectInHistogram(hist, matrix[0].size()) ); } return max_; } int maxRectInHistogram(int hist[], int n) // hist: contains the heights of the bars // n: the number of the bars in the histogram. { int* arr = new int[n];// 申请一个额外的数组 arr[0] = hist[0]; int max = hist[0]; // 最大面积 for(int i=1; i<n; i++) { arr[i] = hist[i]; for(int j=i-1; j>=0; j--) if(arr[j]>arr[i]){ if(arr[j]*(i-j)>max) max = arr[j]*(i-j); arr[j] = arr[i]; } else break; //数组arr里的元素,保持非递减的顺序。 } //重新扫描一边,以更新最大面积 for(int i=0; i<n; i++) if(arr[i]*(n-i)>max) max = arr[i]*(n-i); return max; }
- [LeetCode] 01矩阵中最大矩形 Maximal Rectangle
- LeetCode 85. Maximal Rectangle(最大矩形)
- [LeetCode]Maximal Rectangle寻找最大矩形
- 寻找01矩阵中最大的子矩阵 Maximal Rectangle
- LeetCode 85. Maximal Rectangle(最大子矩阵)
- leetcode 85. Maximal Rectangle 最大子矩阵
- Maximal Rectangle(最大矩阵)
- Maximal Rectangle 最大的矩形
- LeetCode OJ 之 Maximal Rectangle (最大的矩形)
- Leetcode 85. Maximal Rectangle 最大矩形 解题报告
- LeetCode OJ 之 Maximal Rectangle (最大的矩形)
- LeetCode 85 Maximal Rectangle (最大子矩形 单调栈)
- LeetCode 笔记系列 18 Maximal Rectangle [学以致用](最大矩形)
- Maximal Rectangle 二维矩形中最大的1个数
- 求全是1的最大矩阵面积 Maximal Rectangle @LeetCode
- (每日算法)Leetcode --- Maximal Rectangle(最大子矩阵)
- leetcode 85. Maximal Rectangle(最大全1子矩阵)
- Maximal Rectangle 最大的矩形面积
- 网页中的路径问题(转载加个人理解)
- 自定义tab bar控件
- 课程设计——中国象棋中的跳马问题
- 工作流引擎开发系列二数据库设计
- spring学习资料
- [LeetCode] 01矩阵中最大矩形 Maximal Rectangle
- 猛犸代码助手开通官网,最新版本实现程序自动更新升级
- POJ 2115 扩展欧几里得
- Android之初学Appwidget
- iphone开发Objective-C新特性──类别与协议
- Sizeof与Strlen的区别与联系
- linux2.6驱动makefile的编写和驱动编写快速参考
- .ASP.NET跨页面传值技巧
- 二叉查找树