LeetCode之“动态规划”:Maximal Square && Largest Rectangle in Histogram && Maximal Rectangle
2015-06-09 19:39
561 查看
1. Maximal Square
题目链接题目要求:
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.
For example, given the following matrix:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
Return 4.
在GeeksforGeeks有一个解决该问题的方法:
1) Construct a sum matrix S[R][C] for the given M[R][C]. a) Copy first row and first columns as it is from M[][] to S[][] b) For other entries, use following expressions to construct S[][] If M[i][j] is 1 then S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1 Else /*If M[i][j] is 0*/ S[i][j] = 0 2) Find the maximum entry in S[R][C] 3) Using the value and coordinates of maximum entry in S[i], print sub-matrix of M[][]
构造完‘和矩阵S’后,我们只需求得该矩阵的最大值就可以了。
为什么只需求得该最大值就可以了?而且相同的最大值可能有很多个。细想下式我们就会知道‘和矩阵S’中的每一个值表示的都是从其他节点(本结点左上)到本节点所能构成的最大正方形的边长长度。
S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1
具体的程序如下:
class Solution { public: int largestRectangleArea(vector<int>& height) { vector<int> s; int sz = height.size(); height.resize(++sz); int maxArea = 0; int i = 0; while(i < sz) { if(s.empty() || height[i] >= height[s.back()]) { s.push_back(i); i++; } else { int t = s.back(); s.pop_back(); maxArea = max(maxArea, height[t] * (s.empty() ? i : i - s.back() - 1)); } } return maxArea; } int maximalRectangle(vector<vector<char>>& matrix) { int rows = matrix.size(); if(rows == 0) return 0; int cols = matrix[0].size(); vector<vector<int> > height(rows, vector<int>(cols, 0)); for(int i = 0; i < rows; i++) for(int j = 0; j < cols; j++) { if(matrix[i][j] != '0') height[i][j] = (i == 0) ? 1 : height[i-1][j] + 1; } int maxArea = 0; for(int i = 0; i < rows; i++) maxArea = max(maxArea, largestRectangleArea(height[i])); return maxArea; } };
View Code
相关文章推荐
- C语言指针数组和数组指针
- Netlink实现热拔插监控
- 极大似然估计原理思想
- WWDC 2015大会视频直播地址:看iOS9大展身手
- 20150603指针基本操作及应用
- 程序员必读的职业规划书之摘要
- js实现小时钟,js中Date对象的使用?
- NSURLRequestCachePolicy 缓存策略
- 利用HtmlAgilityPack库进行HTML数据抓取
- HttpClient几种实现方式
- Qt5.0 https
- 第14周-输入输出流,文本文件-项目3-OOP版电子词典
- 20150601数组练习
- 20150602函数
- 在Ubuntu Linux下怎样安装QQ
- 一张图记住常用 Linux 系统性能诊断工具
- hdu 5265 pog loves szh II
- sizeHint() minimumSizeHint() sizePolicy() 的使用
- WINRAR4.2破解方式或注册码
- 20150528循环