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: Maximal Rectangle 解题报告

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

  3. [LintCode] Maximal Rectangle 最大矩形

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

  4. [LeetCode] 85. Maximal Rectangle 最大矩形

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

  5. [LeetCode] Perfect Rectangle 完美矩形

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

  6. [leetcode]Maximal Rectangle @ Python

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

  7. [LeetCode] 223. 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(N)

    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. 基于 HTML5 的 WebGL 技术构建 3D 场景(一)

    今天和大家分享的是 3D 系列之 3D 预定义模型. HT for Web 提供了多种基础类型供用户建模使用,不同于传统的 3D 建模方式,HT 的建模核心都是基于 API 的接口方式,通过 HT 预 ...

  2. 如果你也会C#,那不妨了解下F#(6):面向对象编程之“类”

    前言 面向对象的思想已经非常成熟,而使用C#的程序员对面向对象也是非常熟悉,所以我就不对面向对象进行介绍了,在这篇文章中将只会介绍面向对象在F#中的使用. F#是支持面向对象的函数式编程语言,所以你用 ...

  3. Kafka如何创建topic?

    Kafka创建topic命令很简单,一条命令足矣:bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-facto ...

  4. 常用JavaScript触发事件

    事件句柄 onclick=JavaScript:鼠标单击某个对象.3 ondblclick=JavaScript:鼠标双击某个对象.3 onmousedown=JavaScript:某个鼠标键被按下. ...

  5. 在DevExpress中使用CameraControl控件进行摄像头图像采集

    在我们以前的项目了,做摄像头的图片采集,我们一般还是需要做一个封装处理的,在较新版本的DevExpress控件里面,增加了一个CameraControl控件,可以直接调用摄像头显示的,因此也可以做头像 ...

  6. 用JavaScript来实现链表LinkedList

    本文版权归博客园和作者本人共同所有,转载和爬虫请注明原文地址. 写在前面 好多做web开发的朋友,在学习数据结构和算法时可能比较讨厌C和C++,上学的时候写过的也忘得差不多了,更别提没写过的了.但幸运 ...

  7. RedisRepository封装—Redis发布订阅以及StackExchange.Redis中的使用

    本文版权归博客园和作者本人吴双共同所有,转载请注明本Redis系列分享地址.http://www.cnblogs.com/tdws/tag/NoSql/ Redis Pub/Sub模式 基本介绍 Re ...

  8. java重载与覆写

    很多同学对于overload和override傻傻分不清楚,建议不要死记硬背概念性的知识,要理解着去记忆. 先给出我的定义: overload(重载):在同一类或者有着继承关系的类中,一组名称相同,参 ...

  9. HTTP各状态码解释

      状态码 含义 100 客户端应当继续发送请求.这个临时响应是用来通知客户端它的部分请求已经被服务器接收,且仍未被拒绝.客户端应当继续发送请求的剩余部分,或者如果请求已经完成,忽略这个响应.服务器必 ...

  10. Windows安装RabbitMQ集群的几个注意点

    记录一下RabbitMQ在windows平台下安装的几个注意点- -,好记性不如烂笔头 安装过程与Linux安装一致,教程参照官网集群配置:此处只列举出几个注意点: 1. erlang的版本需要一致, ...