-
Notifications
You must be signed in to change notification settings - Fork 892
/
problem_136.py
85 lines (63 loc) · 2.17 KB
/
problem_136.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def extendable_row(matrix, erow, scol, ecol):
return all(matrix[erow][scol:ecol])
def extendable_col(matrix, ecol, srow, erow):
for row in range(srow, erow):
if not matrix[row][ecol]:
return False
return True
def area_helper(matrix, num_rows, num_cols, srow, erow, scol, ecol):
current_area = (erow - srow) * (ecol - scol)
row_ex_area, col_ex_area = 0, 0
ex_row = erow < num_rows and extendable_row(matrix, erow, scol, ecol)
if ex_row:
row_ex_area = area_helper(matrix, num_rows, num_cols,
srow, erow + 1, scol, ecol)
ex_col = ecol < num_cols and extendable_col(matrix, ecol, srow, erow)
if ex_col:
col_ex_area = area_helper(matrix, num_rows, num_cols,
srow, erow, scol, ecol + 1)
return max(current_area, row_ex_area, col_ex_area)
def get_largest_area(matrix):
max_area = 0
if not matrix:
return max_area
num_rows, num_cols = len(matrix), len(matrix[0])
for i in range(num_rows):
for j in range(num_cols):
upper_bound_area = (num_rows - i) * (num_cols - j)
if matrix[i][j] and upper_bound_area > max_area:
area = area_helper(
matrix, num_rows, num_cols, i, i + 1, j, j + 1)
max_area = area if area > max_area else max_area
return max_area
# Tests
matrix = [[1, 0, 0, 0],
[1, 0, 1, 1],
[1, 0, 1, 1],
[0, 1, 0, 0]]
assert get_largest_area(matrix) == 4
matrix = [[1, 0, 0, 0],
[1, 0, 1, 1],
[1, 0, 1, 1],
[0, 1, 1, 1]]
assert get_largest_area(matrix) == 6
matrix = [[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]
assert get_largest_area(matrix) == 16
matrix = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
assert get_largest_area(matrix) == 0
matrix = [[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 0, 0],
[0, 0, 0, 0]]
assert get_largest_area(matrix) == 8
matrix = [[1, 1, 0, 0],
[1, 0, 0, 0],
[1, 0, 0, 0],
[1, 0, 0, 0]]
assert get_largest_area(matrix) == 4