2257. Count Unguarded Cells in the Grid #859
-
Topics: You are given two integers A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it. Return the number of unoccupied cells that are not guarded. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to mark the cells that are guarded by at least one guard. The guards can see in four cardinal directions (north, south, east, and west), but their vision is blocked by walls. We can simulate this process and count the number of cells that are unguarded. Approach:
Steps:
Let's implement this solution in PHP: 2257. Count Unguarded Cells in the Grid <?php
/**
* @param Integer $m
* @param Integer $n
* @param Integer[][] $guards
* @param Integer[][] $walls
* @return Integer
*/
function countUnguarded($m, $n, $guards, $walls) {
// Initialize the grid
$grid = array_fill(0, $m, array_fill(0, $n, 0));
// Define constants for the grid
$GUARD = 1;
$WALL = 2;
$GUARDED = 3;
// Mark walls and guards on the grid
foreach ($walls as $wall) {
list($row, $col) = $wall;
$grid[$row][$col] = $WALL;
}
foreach ($guards as $guard) {
list($row, $col) = $guard;
$grid[$row][$col] = $GUARD;
}
// Directions for north, south, east, west
$directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
// Process guards
foreach ($guards as $guard) {
list($row, $col) = $guard;
foreach ($directions as $dir) {
$x = $row;
$y = $col;
// Move in the current direction
while (true) {
$x += $dir[0];
$y += $dir[1];
// Stop if out of bounds or hits a wall/guard
if ($x < 0 || $x >= $m || $y < 0 || $y >= $n || $grid[$x][$y] == $WALL || $grid[$x][$y] == $GUARD) {
break;
}
// Mark the cell as guarded
if ($grid[$x][$y] == 0) {
$grid[$x][$y] = $GUARDED;
}
}
}
}
// Count unguarded cells
$unguardedCount = 0;
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($grid[$i][$j] == 0) {
$unguardedCount++;
}
}
}
return $unguardedCount;
}
// Example 1
$m = 4;
$n = 6;
$guards = [[0, 0], [1, 1], [2, 3]];
$walls = [[0, 1], [2, 2], [1, 4]];
echo countUnguarded($m, $n, $guards, $walls); // Output: 7
// Example 2
$m = 3;
$n = 3;
$guards = [[1, 1]];
$walls = [[0, 1], [1, 0], [2, 1], [1, 2]];
echo countUnguarded($m, $n, $guards, $walls); // Output: 4
?> Explanation:
Performance:
Time Complexity:
Thus, the overall complexity is O(m * n), which is efficient given the problem constraints. Edge Cases:
|
Beta Was this translation helpful? Give feedback.
We need to mark the cells that are guarded by at least one guard. The guards can see in four cardinal directions (north, south, east, and west), but their vision is blocked by walls. We can simulate this process and count the number of cells that are unguarded.
Approach:
Steps:
Grid Init…