刚才看见一段非常巧妙地算法来这里记录一下Maximum Rectangle
2015-12-02 10:34
435 查看
例:
0 0 0 0
|-----------|
|1 1 1 |1
|1 1 1 |0
|-----------|
0 1 0 0
在一个全是0,1的m * n阶矩阵中,找出包含1最多的子矩阵。
0 0 0 0
|-----------|
|1 1 1 |1
|1 1 1 |0
|-----------|
0 1 0 0
在一个全是0,1的m * n阶矩阵中,找出包含1最多的子矩阵。
class Solution { public: int maximalRectangle(vector<vector<char> > &matrix) { int row = matrix.size(); int col = matrix[0].size(); vector<vector<int> > trans(row, vector<int>(col, 0) ); for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { if(matrix[i][i] == '0') { trans[i][j] = 0; } else { trans[i][j] = i == 0 ? 1 : trans[i - 1][j] + 1; } } } int maxArea = 0; for(int i = 0; i < row; i++) { maxArea = max(maxArea, largestRectangleArea(trans[i])); } return maxArea; } int largestRectangleArea(vector<int>& height) { vector<int> tops; int sum = 0; int index = 0; height.push_back(0); while(index < height.size()) { if(tops.empty() || height[index] > height[tops.back()]) { tops.push_back(index); index++; } else { int cur = tops.back(); tops.pop_back(); int left = tops.back(); int right = index; //sum = height[cur] * (top.empty() ? i : (right - left - 1) ); sum = max(sum, height[cur] * (tops.empty() ? right : (right - left - 1) )); } } return sum; } };
相关文章推荐
- 【CF 应用开发大赛】IT Share(IT分享网)
- 站长有福了-让网址一键添加百度首页导航
- RHEL 6.3 LAMP环境配置 ncurses 出错及解决
- exchange online share mailbox senditem
- 分享到朋友圈和发送给好友
- CPP 虚函数、虚函数表及虚拟继承(转)
- Solaris11添加swap方法
- 在CentOS上安装7zip和使用
- mount
- vbox share file between guest with host
- nginx新手配置$document_root
- MySQL 编码设置
- 关于Metasploit-学习笔记-基础命令以及参数
- Deploying Control Plane Policing
- 教你轻松实现用SCOM监控Linux主机
- 在window下与linux虚拟机建立共享文件夹
- Thrift的required和optional源码分析
- Purpose of the MacroMobile Project 1029 ------- No deletion of any Doc for the project
- String.Empty,NULL和""的区别
- C++算法--图算法读书笔记1