題目:
給定一個僅包含 0 和 1 的二維二進制矩陣,找出只包含 1 的最大矩形,並返回其面積。
思路:
使用head和tail來構建以某點為基准的矩形的寬,使用height來定義以某點為基准的矩形的高。
程序:
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
row = len(matrix)
column = len(matrix[0])
if row <= 0:
return 0
if column <= 0:
return 0
head = [-1] * column
tail = [column] * column
height = [0] * column
result = 0
for index1 in range(row):
current_head = -1
current_tail = column
for index2 in range(column):
if matrix[index1][index2] == "1":
height[index2] += 1
else:
height[index2] = 0
for index2 in range(column):
if matrix[index1][index2] == "1":
head[index2] = max(head[index2], current_head)
else:
head[index2] = -1
current_head = index2
for index2 in range(column - 1, -1, -1):
if matrix[index1][index2] == "1":
tail[index2] = min(tail[index2], current_tail)
else:
tail[index2] = column
current_tail = index2
for index2 in range(column):
result = max(result, (tail[index2] - head[index2] - 1) * height[index2])
return result
