最大矩形-LintCode
来源:互联网 发布:淘宝实名认证手机 编辑:程序博客网 时间:2024/05/22 09:49
给你一个二维矩阵,权值为False和True,找到一个最大的矩形,使得里面的值全部为True,输出它的面积
样例:
给你一个矩阵如下
[ [1, 1, 0, 0, 1], [0, 1, 0, 0, 1], [0, 0, 1, 1, 1], [0, 0, 1, 1, 1], [0, 0, 0, 0, 1]]
输出6
思路:
参考题目“直方图最大矩形覆盖”,将矩阵的每一行当做是直方图来求解。
#ifndef C510_H#define C510_H#include<iostream>#include<vector>#include<stack>using namespace std;class Solution {public: /* * @param matrix: a boolean 2D matrix * @return: an integer */ int maximalRectangle(vector<vector<bool>> &matrix) { // write your code here if (matrix.empty()) return 0; int row = matrix.size(); int col = matrix[0].size(); vector<vector<int>> v(row, vector<int>(col, 0)); for (int j = 0; j < col; ++j) { for (int i = 0; i < row; ++i) { if (matrix[i][j]) { v[i][j] = 1; if (i>0) v[i][j] += v[i - 1][j]; } } } int area = 0; for (auto &c : v) { area = maxVal(largestRectangleArea(c), area); } return area; } int largestRectangleArea(vector<int> &height) { int res = 0; stack<int> s; height.push_back(0); for (int i = 0; i < height.size(); ++i) { if (s.empty() || height[s.top()] < height[i]) s.push(i); else { int cur = s.top(); s.pop(); res = maxVal(res, height[cur] * (s.empty() ? i : (i - s.top() - 1))); --i; } } return res; } int maxVal(int a, int b) { return a > b ? a : b; }};#endif
阅读全文
0 0
- ***[Lintcode]最大矩形
- 最大矩形-LintCode
- LintCode-最大正方形&最大矩形
- LintCode 直方图最大矩形覆盖
- lintcode:直方图最大矩形覆盖
- LintCode-直方图最大矩形覆盖
- 直方图最大矩形覆盖-LintCode
- lintcode[122]:直方图内最大矩形面积
- lintcode(122)直方图最大矩形覆盖
- lintcode 直方图最大矩形覆盖与最大子矩阵
- Lintcode矩形面积
- 最大矩形
- LintCode-最大数
- lintcode-最大数-184
- LintCode: 最大子数组
- LintCode-最大数
- LintCode:最大数
- LintCode 最大数
- Java获取当前学年学期&js判断客户端类型
- spring boot 多线程,异步方法和异步类的注解使用
- 排序-冒泡排序
- 关于Java的几个简单问题
- spring获取数据库连接对象
- 最大矩形-LintCode
- LeetCode.581 Shortest Unsorted Continuous Subarray
- 京东软发的在线笔试
- GraphHttpClient概述
- unity Android 交互
- caffe学习
- 算法11 抓住波粒二象性的火星人
- JEESZ-Redis分布式缓存安装和使用
- JavaWeb+Ueditor上传图片到项目外资源文件