题目分析:
给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。示例:
输入:
[
[“1”,“0”,“1”,“0”,“0”],
[“1”,“0”,“1”,“1”,“1”],
[“1”,“1”,“1”,“1”,“1”],
[“1”,“0”,“0”,“1”,“0”]
]
输出: 6
解题思路:
仔细观察会返现这一题其实和上一题可以用一样的解法解出来,先得到每一列的高度矩阵,再复用上一题的思想求得以每一列为起点的最大面积,最后取所有结果中最大的面积。比如上例从第一行到第四行分别转化为竖着的柱为:(规则就是列为1则加1,为0了直接置位0,你不需要考虑上面的,因为上一层已经算过了)
[1, 0, 1, 0, 0]
[2, 0, 2, 1, 1]
[3, 1, 3, 2, 2]
[4, 0, 0, 3, 0]
然后对四个列表都采用【LeetCode】84. Largest Rectangle in Histogram的方法,再取最大值即可。
测试代码:(Runtime: 88 ms, faster than 89.43 %)
class Solution:
def largestRectangleArea(self, heights: list) -> int:
res = 0
stack = [0]
heights.append(0)
heights.insert(0, 0)
for i in range(len(heights)):
while heights[i] < heights[stack[-1]]:
res = max(res, heights[stack.pop()] * (i - stack[-1] - 1))
stack.append(i)
del heights[0]
del heights[-1]
return res
def maximalRectangle(self, matrix: list) -> int:
if not matrix: return 0
height = [0] * len(matrix[0])
res = 0
for i in range(len(matrix)):
for j in range(len((matrix[0]))):
if matrix[i][j] == '1':
height[j] += 1
else:
height[j] = 0
res = max(res, self.largestRectangleArea(height))
return res
print(Solution().maximalRectangle([["1", "0", "1", "0", "0"],["1", "0", "1", "1", "1"],["1", "1", "1", "1", "1"],["1", "0", "0", "1", "0"]])) #提交时请删除该行