算法课作业系列12——Maximal Rectangle
来源:互联网 发布:中美洲际高铁 知乎 编辑:程序博客网 时间:2024/05/14 23:12
算法课作业系列12
Maximal Rectangle
题目
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
For example, given the following matrix:
1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 6.
思路
这道题我想了很久,但是都一一推翻,一个小时之后,我去了讨论区……
言归正传,这道题的思路我是真的想不到的,我根据题目的特征,也就是长方体,想找对角线来决定,然而都失败了,这里只是列举出我学习到的算法,并不是我自己想到的。
1. 找到左边界和右边界
2. 找到高
我来解释一下,意思就是对于每个位置,找到每一行的左边界和右边界,从而决定有多宽,具体数值根据当前行和上一行的清苦昂决定;那决定高就很好理解了,看看纵向能延展多少,从而根据底和高确定出最后面积
参考代码
class Solution {public: int maximalRectangle(vector<vector<char>>& matrix) { vector<vector<int> > left(matrix.size()); vector<vector<int> > right(matrix.size()); vector<vector<int> > height(matrix.size()); int max = 0; for (int i = 0; i < matrix.size(); i++) { vector<int> tmp(matrix[0].size()); left[i] = tmp; right[i] = tmp; height[i] = tmp; for (int j = 0; j < matrix[0].size(); j++) { if (matrix[i][j] == '0') { left[i][j] = 0; right[i][j] = matrix[0].size(); height[i][j] = 0; } else { int k, l; for (k = j - 1; k >= 0; k--) { if (matrix[i][k] == '0') { break; } } k += 1; for (l = j + 1; l < matrix[0].size(); l++) { if (matrix[i][l] == '0') { break; } } if (i == 0) { left[i][j] = k; right[i][j] = l; height[i][j] = 1; } else { left[i][j] = k > left[i - 1][j]?k:left[i - 1][j]; right[i][j] = l < right[i - 1][j]?l:right[i - 1][j]; height[i][j] = height[i - 1][j] + 1; } } int ret = (right[i][j] - left[i][j]) * height[i][j]; if (ret > max) { max = ret; } } } return max; }};
阅读全文
0 0
- 算法课作业系列12——Maximal Rectangle
- leetcode——Maximal Rectangle
- LeetCode85——Maximal Rectangle
- leetcode——Maximal Rectangle
- leetcode 081 —— Maximal Rectangle
- 13.4—动态规划—Maximal Rectangle
- [leetcode刷题系列]Maximal Rectangle
- 【leetcode】Array——Maximal Rectangle(85)
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Install MongoDB Community Edition on Ubuntu
- CentOS 7.2 安装详解
- 无线AP工程
- 回调
- Leetcode 646. Maximum Length of Pair Chain(算法分析week14)
- 算法课作业系列12——Maximal Rectangle
- FAQ(20):org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'zhangga' is
- 【C#】线程与线程
- Notes:《程序员的自我修养——链接、装载与库》
- 基于OpenCV及Python的数独问题识别与求解(一)图像预处理
- https_request()
- QT5 播放音频文件
- DDR2学习笔记(2)
- 解决Redhat BCM43142不能连接WIFI问题