---
# System prepended metadata

title: 2257. Count Unguarded Cells in the Grid
tags: [Leetcode, Simulation, Medium]

---

# 2257. Count Unguarded Cells in the Grid
###### tags: `Leetcode` `Medium` `Simulation`
Link: https://leetcode.com/problems/count-unguarded-cells-in-the-grid/
## 思路 $O(MN)$ $O(MN)$
Simulation
## Code
```java=
class Solution {
    public int countUnguarded(int m, int n, int[][] guards, int[][] walls) {
        char[][] map = new char[m][n];
        int[][] dirs = {{1,0}, {-1,0}, {0,1}, {0,-1}};
        int count = m*n-guards.length-walls.length;
        for(int[] guard:guards){
            map[guard[0]][guard[1]] = 'G';
        }
        for(int[] wall:walls){
            map[wall[0]][wall[1]] = 'W';
        }
        for(int[] guard:guards){
            int x = guard[0];
            int y = guard[1];
            for(int[] dir:dirs){
                int newx = guard[0]+dir[0];
                int newy = guard[1]+dir[1];
                while(newx>=0 && newx<m && newy>=0 && newy<n && map[newx][newy]!='G' && map[newx][newy]!='W'){
                    if(map[newx][newy]!='P') count--;
                    map[newx][newy]='P';
                    newx += dir[0];
                    newy += dir[1];
                }
            }
        }
        return count;
    }
}
```