Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 90602ad

Browse files
authored
Create Find the Minimum Area to Cover All Ones II.py
Signed-off-by: Erjan <erjan@users.noreply.github.com>
1 parent 7c721bb commit 90602ad

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
'''
2+
You are given a 2D binary array grid. You need to find 3 non-overlapping rectangles having non-zero areas with horizontal and vertical sides such that all the 1's in grid lie inside these rectangles.
3+
4+
Return the minimum possible sum of the area of these rectangles.
5+
6+
Note that the rectangles are allowed to touch.
7+
'''
8+
9+
class Solution:
10+
def minimumSum(self, A: List[List[int]]) -> int:
11+
res = float("inf")
12+
for _ in range(4):
13+
n, m = len(A), len(A[0])
14+
for i in range(1, n):
15+
a1 = self.minimumArea(A[:i])
16+
for j in range(1, m):
17+
part2 = [row[:j] for row in A[i:]]
18+
part3 = [row[j:] for row in A[i:]]
19+
a2 = self.minimumArea(part2)
20+
a3 = self.minimumArea(part3)
21+
res = min(res, a1 + a2 + a3)
22+
for i2 in range(i + 1, n):
23+
part2 = A[i:i2]
24+
part3 = A[i2:]
25+
a2 = self.minimumArea(part2)
26+
a3 = self.minimumArea(part3)
27+
res = min(res, a1 + a2 + a3)
28+
A = self.rotate(A)
29+
return res
30+
31+
def minimumArea(self, A: List[List[int]]) -> int:
32+
if not A or not A[0]:
33+
return 0
34+
n, m = len(A), len(A[0])
35+
left, top, right, bottom = float("inf"), float("inf"), -1, -1
36+
for i in range(n):
37+
for j in range(m):
38+
if A[i][j] == 1:
39+
left = min(left, j)
40+
top = min(top, i)
41+
right = max(right, j)
42+
bottom = max(bottom, i)
43+
if right == -1:
44+
return 0
45+
return (right - left + 1) * (bottom - top + 1)
46+
47+
def rotate(self, A: List[List[int]]) -> List[List[int]]:
48+
n, m = len(A), len(A[0])
49+
return [[A[i][j] for i in range(n-1, -1, -1)] for j in range(m)]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /