Leetcode 2257: Count Unguarded Cells in the Grid

grid47
grid47
Exploring patterns and algorithms
Mar 26, 2024 8 min read

You are given a 0-indexed grid of size m x n. Some cells in the grid are occupied by guards, and some by walls. A guard can observe all cells in the four cardinal directions (north, east, south, and west) from its position unless blocked by a wall or another guard. A cell is considered guarded if at least one guard can see it. Your task is to determine the number of cells that are unoccupied and are not guarded.
Problem
Approach
Steps
Complexity
Input: The input consists of the grid dimensions `m` and `n`, followed by two lists: `guards` and `walls`. The `guards` list contains the positions of guards, and the `walls` list contains the positions of walls in the grid.
Example: m = 5, n = 5, guards = [[0,0],[2,2],[4,4]], walls = [[1,1],[3,3]]
Constraints:
• 1 <= m, n <= 10^5
• 2 <= m * n <= 10^5
• 1 <= guards.length, walls.length <= 5 * 10^4
• 2 <= guards.length + walls.length <= m * n
• guards[i].length == walls[j].length == 2
• 0 <= rowi, rowj < m
• 0 <= coli, colj < n
• All positions in guards and walls are unique.
Output: Return the number of unoccupied and unguarded cells in the grid.
Example: Output: 12
Constraints:
Goal: To count the number of cells that are neither occupied by walls nor guarded by any guard.
Steps:
• Initialize a grid of size `m x n` with all values set to 0 (indicating unoccupied and unguarded cells).
• Mark the cells occupied by walls with a 1.
• Mark the cells occupied by guards with a 3.
• For each guard, mark the cells in the four cardinal directions (north, south, east, and west) as guarded, until a wall or another guard is encountered.
• After processing all guards, count the number of cells that are neither occupied by walls nor guarded.
Goal: Ensure that the solution handles large grid sizes and a significant number of guards and walls efficiently.
Steps:
• The grid size can be very large (up to 10^5), so an efficient solution is required.
• Handle cases where there are no guards or no walls.
Assumptions:
• Each guard can only guard cells in the four cardinal directions, and no diagonal observation is allowed.
• If a guard is at a position, it is not considered unguarded by itself.
Input: m = 5, n = 5, guards = [[0,0],[2,2],[4,4]], walls = [[1,1],[3,3]]
Explanation: The guards will guard cells in the four cardinal directions unless blocked by a wall. After processing the guards and walls, the remaining unguarded and unoccupied cells are counted.

Input: m = 4, n = 4, guards = [[0,0]], walls = [[1,1], [3,3]]
Explanation: The grid has walls at (1,1) and (3,3), and a guard at (0,0). After marking the guarded cells, we count the unguarded ones.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus