题目描述
给定一个仅包含 0
和 1
、大小为 rows x cols
的二维二进制矩阵,找出只包含 1
的最大矩形,并返回其面积。
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] 输出:6 解释:最大矩形如上图所示。
示例 2:
输入:matrix = [["0"]] 输出:0
示例 3:
输入:matrix = [["1"]] 输出:1
思路
逐行累积,每次一行累加完,就去计算柱状图中最大的矩形:leetcode-84. 柱状图中最大的矩形-CSDN博客【先做84题,在做本题】
class Solution(object):
def max_area(self, heights):
heights = [0]+heights+[0] # 这里以后改成这么写
res = 0
stack = [0]
for i in range(1, len(heights)):
if heights[i]>heights[stack[-1]]:
stack.append(i)
elif heights[i] == heights[stack[-1]]:
stack.pop()
stack.append(i)
else:
while stack and heights[i]<heights[stack[-1]]:
mid = stack[-1]
stack.pop()
if stack:
right = i
left = stack[-1]
w = right-left-1
h = heights[mid]
res = max(res, w*h)
stack.append(i)
return res
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
m,n = len(matrix), len(matrix[0])
heights = [0]*n
max_area = 0
# 助行累加
for i in range(m):
for j in range(n):
if matrix[i][j]=='1':
heights[j]+=1
else:
heights[j] = 0
max_area = max(max_area, self.max_area(heights))
return max_area
if __name__ == '__main__':
s = Solution()
# matrix = [["1"]]
matrix = [["1", "0", "1", "0", "0"],
["1", "0", "1", "1", "1"],
["1", "1", "1", "1", "1"],
["1", "0", "0", "1", "0"]]
# matrix = [["1","0"],["1","0"]]
print(s.maximalRectangle(matrix))