2290. Minimum Obstacle Removal to Reach Corner #887
-
Topics: You are given a 0-indexed 2D integer array
You can move up, down, left, or right from and to an empty cell. Return the minimum number of obstacles to remove so you can move from the upper left corner Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to model this problem using a graph where each cell in the grid is a node. The goal is to navigate from the top-left corner Approach:
Let's implement this solution in PHP: 2290. Minimum Obstacle Removal to Reach Corner <?php
/**
* @param Integer[][] $grid
* @return Integer
*/
function minimumObstacles($grid) {
$rows = count($grid);
$cols = count($grid[0]);
// Directions for moving up, down, left, right
$directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
// Deque for 0-1 BFS
$deque = new SplDoublyLinkedList();
$deque->push([0, 0, 0]); // [row, col, cost]
// Visited array
$visited = array_fill(0, $rows, array_fill(0, $cols, false));
$visited[0][0] = true;
// 0-1 BFS
while (!$deque->isEmpty()) {
list($x, $y, $cost) = $deque->shift();
// If we reach the bottom-right corner, return the cost
if ($x == $rows - 1 && $y == $cols - 1) {
return $cost;
}
// Explore neighbors
foreach ($directions as $direction) {
$nx = $x + $direction[0];
$ny = $y + $direction[1];
// Check if the new position is within bounds and not visited
if ($nx >= 0 && $nx < $rows && $ny >= 0 && $ny < $cols && !$visited[$nx][$ny]) {
$visited[$nx][$ny] = true;
// If no obstacle, add to the front of the deque
if ($grid[$nx][$ny] == 0) {
$deque->unshift([$nx, $ny, $cost]);
} else {
// If obstacle, add to the back of the deque
$deque->push([$nx, $ny, $cost + 1]);
}
}
}
}
return -1; // Should not reach here if there's a valid path
}
// Test Case 1
$grid1 = [
[0, 1, 1],
[1, 1, 0],
[1, 1, 0]
];
echo minimumObstacles($grid1) . PHP_EOL; // Output: 2
// Test Case 2
$grid2 = [
[0, 1, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 1, 0]
];
echo minimumObstacles($grid2) . PHP_EOL; // Output: 0
?> Explanation:
Complexity:
This implementation works efficiently within the given constraints. |
Beta Was this translation helpful? Give feedback.
We need to model this problem using a graph where each cell in the grid is a node. The goal is to navigate from the top-left corner
(0, 0)
to the bottom-right corner(m-1, n-1)
, while minimizing the number of obstacles (1s) we need to remove.Approach:
Graph Representation:
1
(obstacle), the cost is1
(remove the obstacle), and if it moves through a0
(empty cell), the cost is0
.Algorithm Choice: