Skip to content

Commit b849e70

Browse files
committed
最大矩形
1 parent 9e2ad10 commit b849e70

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

maximal_rectangle.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param {boolean[][]} matrix, a list of lists of boolean
5+
# @return {int} an integer
6+
def maximalRectangle(self, matrix):
7+
# Write your code here
8+
if not matrix:
9+
return 0
10+
ret = 0
11+
rows, cols = len(matrix), len(matrix[0])
12+
height = [0] * cols
13+
left, right = [0] * cols, [cols] * cols
14+
# TODO
15+
for i in xrange(rows):
16+
cur_left, cur_right = 0, cols
17+
# 更新当前列的高度
18+
for j in xrange(cols):
19+
height[j] = (height[j] + 1) if matrix[i][j] else 0
20+
# 更新列上元素所属矩阵的左边界
21+
for j in xrange(cols):
22+
if matrix[i][j]:
23+
left[j] = max(left[j], cur_left)
24+
else:
25+
left[j] = 0
26+
cur_left = j + 1
27+
# 更新列上元素所属矩阵的右边界,不减1是方便后面计算宽度。
28+
for j in xrange(cols - 1, -1, -1):
29+
if matrix[i][j]:
30+
right[j] = min(right[j], cur_right)
31+
else:
32+
right[j] = cols
33+
cur_right = j
34+
# 根据左右矩阵的计算方式,max和min函数保证在范围内height[j]有效。
35+
for j in xrange(cols):
36+
ret = max(ret, (right[j] - left[j]) * height[j])
37+
return ret

0 commit comments

Comments
 (0)