3195. Find the Minimum Area to Cover All Ones I
Description
You are given a 2D binary array grid
. Find a rectangle with horizontal and vertical sides with the smallest area, such that all the 1's in grid
lie inside this rectangle.
Return the minimum possible area of the rectangle.
Example 1:
Input: grid = [[0,1,0],[1,0,1]]
Output: 6
Explanation:
The smallest rectangle has a height of 2 and a width of 3, so it has an area of 2 * 3 = 6
.
Example 2:
Input: grid = [[1,0],[0,0]]
Output: 1
Explanation:
The smallest rectangle has both height and width 1, so its area is 1 * 1 = 1
.
Constraints:
1 <= grid.length, grid[i].length <= 1000
grid[i][j]
is either 0 or 1.- The input is generated such that there is at least one 1 in
grid
.
Solutions
Solution 1: Find Minimum and Maximum Boundaries
We can traverse grid
, finding the minimum boundary of all 1
s, denoted as $(x_1, y_1)$, and the maximum boundary, denoted as $(x_2, y_2)$. Then, the area of the minimum rectangle is $(x_2 - x_1 + 1) \times (y_2 - y_1 + 1)$.
The time complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows and columns in grid
, respectively. The space complexity is $O(1)$.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|