[LeetCode] Maximal Rectangle 最大矩形

时间:2022-08-31 14:11:00

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

Example:

Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6

此题是之前那道的 Largest Rectangle in Histogram 的扩展,这道题的二维矩阵每一层向上都可以看做一个直方图,输入矩阵有多少行,就可以形成多少个直方图,对每个直方图都调用 Largest Rectangle in Histogram 中的方法,就可以得到最大的矩形面积。那么这道题唯一要做的就是将每一层都当作直方图的底层,并向上构造整个直方图,由于题目限定了输入矩阵的字符只有 '0' 和 '1' 两种,所以处理起来也相对简单。方法是,对于每一个点,如果是 ‘0’,则赋0,如果是 ‘1’,就赋之前的 height 值加上1。具体参见代码如下:

解法一:

class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
int res = ;
vector<int> height;
for (int i = ; i < matrix.size(); ++i) {
height.resize(matrix[i].size());
for (int j = ; j < matrix[i].size(); ++j) {
height[j] = matrix[i][j] == '' ? : ( + height[j]);
}
res = max(res, largestRectangleArea(height));
}
return res;
}
int largestRectangleArea(vector<int>& height) {
int res = ;
stack<int> s;
height.push_back();
for (int i = ; i < height.size(); ++i) {
if (s.empty() || height[s.top()] <= height[i]) s.push(i);
else {
int tmp = s.top(); s.pop();
res = max(res, height[tmp] * (s.empty() ? i : (i - s.top() - )));
--i;
}
}
return res;
}
};

我们也可以在一个函数内完成,这样代码看起来更加简洁一些,注意这里的 height 初始化的大小为 n+1,为什么要多一个呢?这是因为我们只有在当前位置小于等于前一个位置的高度的时候,才会去计算矩形的面积,假如最后一个位置的高度是最高的,那么我们就没法去计算并更新结果 res 了,所以要在最后再加一个高度0,这样就一定可以计算前面的矩形面积了,这跟上面解法子函数中给 height 末尾加一个0是一样的效果,参见代码如下:

解法二:

class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.empty() || matrix[].empty()) return ;
int res = , m = matrix.size(), n = matrix[].size();
vector<int> height(n + );
for (int i = ; i < m; ++i) {
stack<int> s;
for (int j = ; j < n + ; ++j) {
if (j < n) {
height[j] = matrix[i][j] == '' ? height[j] + : ;
}
while (!s.empty() && height[s.top()] >= height[j]) {
int cur = s.top(); s.pop();
res = max(res, height[cur] * (s.empty() ? j : (j - s.top() - )));
}
s.push(j);
}
}
return res;
}
};

下面这种方法的思路很巧妙,height 数组和上面一样,这里的 left 数组表示若当前位置是1且与其相连都是1的左边界的位置(若当前 height 是0,则当前 left 一定是0),right 数组表示若当前位置是1且与其相连都是1的右边界的位置再加1(加1是为了计算长度方便,直接减去左边界位置就是长度),初始化为n(若当前 height 是0,则当前 right 一定是n),那么对于任意一行的第j个位置,矩形为 (right[j] - left[j]) * height[j],我们举个例子来说明,比如给定矩阵为:

[
[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]
]

第0行:

h:
l:
r:

第1行:

h:
l:
r:

第2行:

h:
l:
r:

第3行:

h:
l:
r:

第4行:

h:
l:
r:

解法三:

class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.empty() || matrix[].empty()) return ;
int res = , m = matrix.size(), n = matrix[].size();
vector<int> height(n, ), left(n, ), right(n, n);
for (int i = ; i < m; ++i) {
int cur_left = , cur_right = n;
for (int j = ; j < n; ++j) {
if (matrix[i][j] == '') {
++height[j];
left[j] = max(left[j], cur_left);
} else {
height[j] = ;
left[j] = ;
cur_left = j + ;
}
}
for (int j = n - ; j >= ; --j) {
if (matrix[i][j] == '') {
right[j] = min(right[j], cur_right);
} else {
right[j] = n;
cur_right = j;
}
res = max(res, (right[j] - left[j]) * height[j]);
}
}
return res;
}
};

再来看一种解法,这里我们统计每一行的连续1的个数,使用一个数组 h_max, 其中 h_max[i][j] 表示第i行,第j个位置水平方向连续1的个数,若 matrix[i][j] 为0,那对应的 h_max[i][j] 也一定为0。统计的过程跟建立累加和数组很类似,唯一不同的是遇到0了要将 h_max 置0。这个统计好了之后,只需要再次遍历每个位置,首先每个位置的 h_max 值都先用来更新结果 res,因为高度为1也可以看作是矩形,然后我们向上方遍历,上方 (i, j-1) 位置也会有 h_max 值,但是用二者之间的较小值才能构成矩形,用新的矩形面积来更新结果 res,这样一直向上遍历,直到遇到0,或者是越界的时候停止,这样就可以找出所有的矩形了,参见代码如下:

解法四:

class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.empty() || matrix[].empty()) return ;
int res = , m = matrix.size(), n = matrix[].size();
vector<vector<int>> h_max(m, vector<int>(n));
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
if (matrix[i][j] == '') continue;
if (j > ) h_max[i][j] = h_max[i][j - ] + ;
else h_max[i][] = ;
}
}
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
if (h_max[i][j] == ) continue;
int mn = h_max[i][j];
res = max(res, mn);
for (int k = i - ; k >= && h_max[k][j] != ; --k) {
mn = min(mn, h_max[k][j]);
res = max(res, mn * (i - k + ));
}
}
}
return res;
}
};

类似题目:

Maximal Square

Largest Rectangle in Histogram

参考资料:

https://leetcode.com/problems/maximal-rectangle/

https://leetcode.com/problems/maximal-rectangle/discuss/29054/Share-my-DP-solution

https://leetcode.com/problems/maximal-rectangle/discuss/29172/My-O(n3)-solution-for-your-reference

https://leetcode.com/problems/maximal-rectangle/discuss/225690/Java-solution-with-explanations-in-Chinese

https://leetcode.com/problems/maximal-rectangle/discuss/29064/A-O(n2)-solution-based-on-Largest-Rectangle-in-Histogram

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Maximal Rectangle 最大矩形的更多相关文章

  1. leetcode Maximal Rectangle 单调栈

    作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4052721.html 题目链接:leetcode Maximal Rectangle 单调栈 ...

  2. LeetCode&colon; Maximal Rectangle 解题报告

    Maximal RectangleGiven a 2D binary matrix filled with 0's and 1's, find the largest rectangle contai ...

  3. &lbrack;LintCode&rsqb; Maximal Rectangle 最大矩形

    Given a 2D boolean matrix filled with False and True, find the largest rectangle containing all True ...

  4. &lbrack;LeetCode&rsqb; 85&period; Maximal Rectangle 最大矩形

    Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and ...

  5. &lbrack;LeetCode&rsqb; Perfect Rectangle 完美矩形

    Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover o ...

  6. &lbrack;leetcode&rsqb;Maximal Rectangle &commat; Python

    原题地址:https://oj.leetcode.com/problems/maximal-rectangle/ 题意:Given a 2D binary matrix filled with 0's ...

  7. &lbrack;LeetCode&rsqb; 223&period; Rectangle Area 矩形面积

    Find the total area covered by two rectilinearrectangles in a 2D plane. Each rectangle is defined by ...

  8. leetcode -- Maximal Rectangle TODO O&lpar;N&rpar;

    Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and ...

  9. 085 Maximal Rectangle 最大矩形

    给定一个填充了 0 和 1 的二进制矩阵,找到最大的只包含 1 的矩形并返回其面积.例如,给出以下矩阵:1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0返回 6 详见:http ...

随机推荐

  1. fork详解

    [本文链接] http://www.cnblogs.com/hellogiser/p/fork.html [代码] 下面的代码输出多少个-?  C++ Code  123456789101112131 ...

  2. python字符串关键点总结

    python字符串关键点有下面几点: 1.一些引号分隔的字符 你可以把字符串看出是Python的一种数据类型,在Python单引号或者双引号之间的字符数组或者连续的字符集合.在python中最常用的引 ...

  3. &lbrack;转&rsqb;SQL语句优化技术分析

    一.操作符优化 1.IN 操作符 用IN写出来的SQL的优点是比较容易写及清晰易懂,这比较适合现代软件开发的风格.但是用IN的SQL性能总是比较低的,从Oracle执行的步骤来分析用IN的SQL与不用 ...

  4. 使用Win7&plus;IIS7发布网站或服务步骤

    1.安装IIS服务:控制面板=>程序=>打开或关闭WINDOWS 功能=>Internet 信息服务=>WEB服务管理器全选√ 和万维网服务:应用程序开发功能: 2.打开IIS ...

  5. C&num; TCP多线程服务器示例

    前言 之前一直很少接触多线程这块.这次项目中刚好用到了网络编程TCP这块,做一个服务端,需要使用到多线程,所以记录下过程.希望可以帮到自己的同时能给别人带来一点点收获- 关于TCP的介绍就不多讲,神马 ...

  6. 201521123011《Java程序设计》第6周学习总结

    1. 本周学习总结 1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图,对面向对象思想进行一个总结. XMind 2. 书面作业 1.clone方法 1.1 O ...

  7. 写一个简单的配置文件和日志管理(shell)

    最近在做一个Linux系统方案的设计,写了一个之前升级服务程序的配置和日志管理. 共4个文件,服务端一个UpdateServer.conf配置文件和一个UpdateServer脚本,客户端一个Upda ...

  8. WPF 客户端浏览器 添加Loading加载进度

    在windows开发界面时,使用浏览器来请求和显示网页内容,是比较常见的. 但是在请求网页内容时,因网速或者前端功能复杂加载较慢,亦或者加载时遇到各种问题,如空白/黑屏/加载不完整/证书问题等. 因此 ...

  9. 【转】IIS - 自动申请、部署Let&&num;39&semi;s Encrypt的免费SSL证书

    IIS - 自动申请.部署Let's Encrypt的免费SSL证书(让网站实现HTTPS协议) 2017-12-19发布:hangge阅读:161   一.HTTPS 协议介绍 1,什么是 HTTP ...

  10. Logstash filter 的使用

    原文地址:http://techlog.cn/article/list/10182917 概述 logstash 之所以强大和流行,与其丰富的过滤器插件是分不开的 过滤器提供的并不单单是过滤的功能,还 ...