您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: