给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
class Solution:
def max_area(self,heights):
stack = [-1]
res = 0
for i in range(len(heights)):
while (stack[-1] != -1 and heights[i] <= heights[stack[-1]]):
res = max(res, heights[stack.pop()] * (i - stack[-1] - 1))
stack.append(i)
while (stack[-1] != -1):
res = max(res, heights[stack.pop()] * (len(heights) - stack[-1] - 1))
return res
def maximalRectangle(self, matrix: List[List[str]]) -> int:
res = 0
if len(matrix) == 0 or len(matrix[0]) == 0:
return res
heights = [0] * len(matrix[0])
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == '0':
heights[j] = 0
else:
heights[j] += 1
res = max(res, self.max_area(heights))
return res
def max_area(heights):
stack = [-1]
res = 0
for i in range(len(heights)):
while (stack[-1] != -1 and heights[i] <= heights[stack[-1]]):
res = max(res, heights[stack.pop()] * (i - stack[-1] - 1))
stack.append(i)
while (stack[-1] != -1):
res = max(res, heights[stack.pop()] * (len(heights) - stack[-1] - 1))
return res
def maximalRectangle(matrix):
res = 0
if len(matrix) == 0 or len(matrix[0]) == 0:
return res
heights = [0] * len(matrix[0])
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == '0':
heights[j] = 0
else:
heights[j] += 1
print(heights)
res = max(res, max_area(heights))
return res
matrix = [["0","1"],["1","0"]]
print(maximalRectangle(matrix))