-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2257-count-unguarded-cells-in-the-grid.js
More file actions
59 lines (54 loc) · 1.73 KB
/
2257-count-unguarded-cells-in-the-grid.js
File metadata and controls
59 lines (54 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* 2257. Count Unguarded Cells in the Grid
* https://leetcode.com/problems/count-unguarded-cells-in-the-grid/
* Difficulty: Medium
*
* 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.
*/
/**
* @param {number} m
* @param {number} n
* @param {number[][]} guards
* @param {number[][]} walls
* @return {number}
*/
var countUnguarded = function(m, n, guards, walls) {
const grid = Array.from({ length: m }, () => Array(n).fill(0));
for (const [row, col] of walls) {
grid[row][col] = 1;
}
for (const [row, col] of guards) {
grid[row][col] = 2;
}
for (const [row, col] of guards) {
for (let i = row - 1; i >= 0 && grid[i][col] !== 1 && grid[i][col] !== 2; i--) {
grid[i][col] = 3;
}
for (let i = row + 1; i < m && grid[i][col] !== 1 && grid[i][col] !== 2; i++) {
grid[i][col] = 3;
}
for (let j = col - 1; j >= 0 && grid[row][j] !== 1 && grid[row][j] !== 2; j--) {
grid[row][j] = 3;
}
for (let j = col + 1; j < n && grid[row][j] !== 1 && grid[row][j] !== 2; j++) {
grid[row][j] = 3;
}
}
let result = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 0) {
result++;
}
}
}
return result;
};