Count Unguarded Cells in the Grid LeetCode solution in JavaScript

1
var countUnguarded = function (m, n, guards, walls) {
2
let board = new Array(m).fill(0).map((_) => new Array(n).fill(0));
3

4
// 0 - Empty
5
// 1 - Guard
6
// 2 - Wall
7
// 3 - Guard view
8

9
const DIRECTIONS = [
10
[-1, 0],
11
[0, 1],
12
[1, 0],
13
[0, -1],
14
];
15

16
for (let [guardRow, guardCol] of guards) board[guardRow][guardCol] = 1;
17

18
for (let [wallRow, wallCol] of walls) board[wallRow][wallCol] = 2;
19

20
for (let [guardRow, guardCol] of guards) {
21
//Loop through row with the same col
22
//Go down from current row
23
let row = guardRow + 1;
24
while (row < m) {
25
//Stop if you encounter a wall or guard
26
if (board[row][guardCol] == 1 || board[row][guardCol] == 2) break;
27
board[row][guardCol] = 3;
28
row++;
29
}
30
//Go up from current row
31
row = guardRow - 1;
32
while (row >= 0) {
33
if (board[row][guardCol] == 1 || board[row][guardCol] == 2) break;
34
board[row][guardCol] = 3;
35
row--;
36
}
37

38
//Loop through col with the same row
39
//Go right from current col
40
let col = guardCol + 1;
41
while (col < n) {
42
if (board[guardRow][col] == 1 || board[guardRow][col] == 2) break;
43
board[guardRow][col] = 3;
44
col++;
45
}
46

47
//Go left from current col
48
col = guardCol - 1;
49
while (col >= 0) {
50
if (board[guardRow][col] == 1 || board[guardRow][col] == 2) break;
51
board[guardRow][col] = 3;
52
col--;
53
}
54
}
55

56
//Count the free cells
57
let freeCount = 0;
58
for (let i = 0; i < m; i++) {
59
for (let j = 0; j < n; j++) {
60
if (board[i][j] == 0) freeCount++;
61
}
62
}
63

64
return freeCount;
65
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0