2257. Count Unguarded Cells in the Grid
Difficulty: Medium
Topics: Array, Matrix, Simulation
You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively.
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:
Solution:
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.
Grid Initialization: Create a 2D array to represent the grid. Mark cells with walls, guards, and guarded areas as we iterate.
Simulating Guard Coverage:
Counting Unguarded Cells: After processing all guards, count cells that are neither walls, guards, nor guarded.
Let's implement this solution in PHP: 2257. Count Unguarded Cells in the Grid
Explanation:
Initialization:
- The grid is initialized with 0 for empty cells. Walls and guards are marked with unique constants.
Guard Simulation:
- For each guard, simulate movement in all four directions, marking cells as guarded until hitting a wall or another guard.
Counting Unguarded Cells:
- After processing all guards, iterate through the grid and count cells still marked as 0.
Performance:
Thus, the overall complexity is O(m * n), which is efficient given the problem constraints.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Count Unguarded Cells in the Grid. For more information, please follow other related articles on the PHP Chinese website!