最大矩形搜素法的python代码实现
时间: 2023-07-23 11:12:10 浏览: 120
以下是最大矩形搜索法的 Python 代码实现:
```python
def max_rectangle(matrix):
if not matrix or not matrix[0]:
return 0
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] == 0:
heights[j] = 0
else:
heights[j] += 1
stack = [-1]
for k in range(n):
while stack[-1] != -1 and heights[stack[-1]] >= heights[k]:
h = heights[stack.pop()]
w = k - stack[-1] - 1
max_area = max(max_area, h * w)
stack.append(k)
while stack[-1] != -1:
h = heights[stack.pop()]
w = n - stack[-1] - 1
max_area = max(max_area, h * w)
return max_area
```
该代码接受一个二维矩阵作为输入,返回该矩阵中最大矩形的面积。其中,heights 列表用于记录每一行的高度,stack 列表用于存储当前的递增高度序列。具体实现方法可参考注释。
阅读全文