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
|
from typing import List
class Solution:
# Method 2: optimized partition-based enumeration using area_of_ones helper
def minimumSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
INF = 10**9
ans = INF
# 1) Top block + two blocks in the bottom row (split by a vertical line)
for i in range(m):
one = self.area_of_ones(grid, 0, i, 0, n - 1)
for j in range(n):
two = self.area_of_ones(grid, i + 1, m - 1, 0, j)
three = self.area_of_ones(grid, i + 1, m - 1, j + 1, n - 1)
ans = min(ans, one + two + three)
# 2) Left block + two blocks on the right (split by a horizontal line)
for j in range(n):
one = self.area_of_ones(grid, 0, m - 1, 0, j)
for i in range(m):
two = self.area_of_ones(grid, 0, i, j + 1, n - 1)
three = self.area_of_ones(grid, i + 1, m - 1, j + 1, n - 1)
ans = min(ans, one + two + three)
# 3) Right block + two blocks on the left (mirror of previous)
for j in range(n - 1, -1, -1):
one = self.area_of_ones(grid, 0, m - 1, j + 1, n - 1)
for i in range(m):
two = self.area_of_ones(grid, 0, i, 0, j)
three = self.area_of_ones(grid, i + 1, m - 1, 0, j)
ans = min(ans, one + two + three)
# 4) Bottom block + two blocks on the top (mirror of 1)
for i in range(m - 1, -1, -1):
one = self.area_of_ones(grid, i + 1, m - 1, 0, n - 1)
for j in range(n):
two = self.area_of_ones(grid, 0, i, 0, j)
three = self.area_of_ones(grid, 0, i, j + 1, n - 1)
ans = min(ans, one + two + three)
# 5) Three horizontal strips
for i in range(m):
for j in range(i + 1, m):
one = self.area_of_ones(grid, 0, i, 0, n - 1)
two = self.area_of_ones(grid, i + 1, j, 0, n - 1)
three = self.area_of_ones(grid, j + 1, m - 1, 0, n - 1)
ans = min(ans, one + two + three)
# 6) Three vertical strips
for i in range(n):
for j in range(i + 1, n):
one = self.area_of_ones(grid, 0, m - 1, 0, i)
two = self.area_of_ones(grid, 0, m - 1, i + 1, j)
three = self.area_of_ones(grid, 0, m - 1, j + 1, n - 1)
ans = min(ans, one + two + three)
return 0 if ans == INF else ans
def area_of_ones(self, grid: List[List[int]], st_i: int, en_i: int, st_j: int, en_j: int) -> int:
# inclusive bounds; return 0 if invalid range or no ones
if st_i > en_i or st_j > en_j:
return 0
minr, maxr = 10**9, -1
minc, maxc = 10**9, -1
found = False
for i in range(st_i, en_i + 1):
for j in range(st_j, en_j + 1):
if grid[i][j] == 1:
found = True
minr = min(minr, i)
maxr = max(maxr, i)
minc = min(minc, j)
maxc = max(maxc, j)
return (maxr - minr + 1) * (maxc - minc + 1) if found else 0
|