3195. Find the Minimum Area to Cover All Ones I #2082
-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the smallest rectangle with sides parallel to the grid that can cover all the 1's in a given binary matrix. The solution involves determining the boundaries of the rectangle by identifying the extreme positions (topmost, bottommost, leftmost, and rightmost) of the 1's in the grid. Approach
Let's implement this solution in PHP: 3195. Find the Minimum Area to Cover All Ones I <?php
/**
* @param Integer[][] $grid
* @return Integer
*/
function minimumArea($grid) {
$rows = count($grid);
$cols = count($grid[0]);
$minRow = $rows;
$maxRow = -1;
$minCol = $cols;
$maxCol = -1;
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
if ($grid[$i][$j] == 1) {
if ($i < $minRow) {
$minRow = $i;
}
if ($i > $maxRow) {
$maxRow = $i;
}
if ($j < $minCol) {
$minCol = $j;
}
if ($j > $maxCol) {
$maxCol = $j;
}
}
}
}
$height = $maxRow - $minRow + 1;
$width = $maxCol - $minCol + 1;
return $height * $width;
}
// Test cases
// Example 1
$grid1 = array(
array(0,1,0),
array(1,0,1)
);
echo minimumArea($grid1) . "\n"; // Output: 6
// Example 2
$grid2 = array(
array(1,0),
array(0,0)
);
echo minimumArea($grid2) . "\n"; // Output: 1
?> Explanation:
This approach efficiently determines the required rectangle by leveraging simple boundary checks during a single pass through the grid, ensuring optimal performance with a time complexity of O(n*m), where n and m are the dimensions of the grid. |
Beta Was this translation helpful? Give feedback.
We need to find the smallest rectangle with sides parallel to the grid that can cover all the 1's in a given binary matrix. The solution involves determining the boundaries of the rectangle by identifying the extreme positions (topmost, bottommost, leftmost, and rightmost) of the 1's in the grid.
Approach