You are given two integers m and n representing a 0-indexedm 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 notguarded.
Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]Output: 7Explanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram.There are a total of 7 unguarded cells, so we return 7.
Input: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]Output: 4Explanation: The unguarded cells are shown in green in the above diagram.There are a total of 4 unguarded cells, so we return 4.
class Solution: # Time: O(m * n); every cell is scanned a constant number of times. # Space: O(m * n) for the grid. def count_unguarded( self, m: int, n: int, guards: list[list[int]], walls: list[list[int]] ) -> int: grid = [[0] * n for _ in range(m)] for row, col in guards: grid[row][col] = 1 for row, col in walls: grid[row][col] = 2 for row, col in guards: for d_row, d_col in ((-1, 0), (1, 0), (0, -1), (0, 1)): next_row, next_col = row + d_row, col + d_col while ( 0 <= next_row < m and 0 <= next_col < n and grid[next_row][next_col] in (0, 3) ): grid[next_row][next_col] = 3 next_row += d_row next_col += d_col return sum(row.count(0) for row in grid)