Find the Minimum Area to Cover All Ones II Problem
Description
LeetCode Problem 3197.
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.
Return the minimum possible sum of the area of these rectangles.
Note that the rectangles are allowed to touch.
Example 1:
Input: grid = [[1,0,1],[1,1,1]]
Output: 5
Explanation:

- The 1's at (0, 0) and (1, 0) are covered by a rectangle of area 2.
- The 1's at (0, 2) and (1, 2) are covered by a rectangle of area 2.
- The 1 at (1, 1) is covered by a rectangle of area 1.
Example 2:
Input: grid = [[1,0,1,0],[0,1,0,1]]
Output: 5
Explanation:

- The 1's at (0, 0) and (0, 2) are covered by a rectangle of area 3.
- The 1 at (1, 1) is covered by a rectangle of area 1.
- The 1 at (1, 3) is covered by a rectangle of area 1.
Constraints:
1 <= grid.length, grid[i].length <= 30grid[i][j]is either 0 or 1.- The input is generated such that there are at least three 1's in
grid.
Solution
Approach: Enumerating Two Cuts
Three non-overlapping rectangles that cover every 1 can always be separated by two cuts. There are six ways to place them:
- Two horizontal cuts (three stacked strips).
- Two vertical cuts (three side-by-side strips).
- One horizontal cut, then split the upper part vertically.
- One horizontal cut, then split the lower part vertically.
- One vertical cut, then split the left part horizontally.
- One vertical cut, then split the right part horizontally.
Let f(i1, j1, i2, j2) be the area of the smallest rectangle containing every 1 inside the region from (i1, j1) to (i2, j2) (found by scanning the region for the extreme rows and columns). Try every cut position for each of the six layouts and keep the smallest sum of three areas.
Complexity: O(m2n2) time and O(1) extra space.
from math import inf
class Solution:
def minimumSum(self, grid: List[List[int]]) -> int:
def f(i1: int, j1: int, i2: int, j2: int) -> int:
x1 = y1 = inf
x2 = y2 = -inf
for i in range(i1, i2 + 1):
for j in range(j1, j2 + 1):
if grid[i][j] == 1:
x1 = min(x1, i)
y1 = min(y1, j)
x2 = max(x2, i)
y2 = max(y2, j)
return (x2 - x1 + 1) * (y2 - y1 + 1)
m, n = len(grid), len(grid[0])
ans = m * n
for i1 in range(m - 1):
for i2 in range(i1 + 1, m - 1):
ans = min(
ans,
f(0, 0, i1, n - 1)
+ f(i1 + 1, 0, i2, n - 1)
+ f(i2 + 1, 0, m - 1, n - 1),
)
for j1 in range(n - 1):
for j2 in range(j1 + 1, n - 1):
ans = min(
ans,
f(0, 0, m - 1, j1)
+ f(0, j1 + 1, m - 1, j2)
+ f(0, j2 + 1, m - 1, n - 1),
)
for i in range(m - 1):
for j in range(n - 1):
ans = min(
ans,
f(0, 0, i, j) + f(0, j + 1, i, n - 1) + f(i + 1, 0, m - 1, n - 1),
)
ans = min(
ans,
f(0, 0, i, n - 1)
+ f(i + 1, 0, m - 1, j)
+ f(i + 1, j + 1, m - 1, n - 1),
)
ans = min(
ans,
f(0, 0, i, j) + f(i + 1, 0, m - 1, j) + f(0, j + 1, m - 1, n - 1),
)
ans = min(
ans,
f(0, 0, m - 1, j)
+ f(0, j + 1, i, n - 1)
+ f(i + 1, j + 1, m - 1, n - 1),
)
return ans