LeetCode 85. Maximal Rectangle
Description
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
在给出的矩阵中,1
表示元素,0
表示空,找出最大矩形的面积。
Solution
本题可以利用《84. Largest Rectangle in Histogram》 的代码。
下面来看看如何转换成 84 题的直方图求解问题:
矩阵:
[10100]
[10111]
[11111]
[10010]
第一行,将 0 及其上方元素去掉:
[1 1 ]
第二行,将 0 及其上方元素去掉:
[1 1 ]
[1 111]
第三行,将 0 及其上方元素去掉:
[1 1 ]
[1 111]
[11111]
第四行,将 0 及其上方元素去掉:
[1 ]
[1 1 ]
[1 1 ]
[1 1 ]
通过四次转换,其实得到四个直方图:
[10100]、[20211]、[31322]、[4030]
至此已将矩阵问题转换成了之前的直方图问题。使用相应代码求解即可。
下面largestRectangleArea
的代码点击这里查看。
|
|