Grid Illumination LeetCode solution in JavaScript

1
var gridIllumination = function (n, lamps, queries) {
2
const directions = [
3
[0, 0],
4
[-1, -1],
5
[-1, 0],
6
[-1, 1],
7
[0, -1],
8
[0, 1],
9
[1, -1],
10
[1, 0],
11
[1, 1],
12
];
13
const lampCoord = new Map();
14
const rowHash = {},
15
colHash = {},
16
leftDiag = {},
17
rightDiag = {};
18

19
// First, illuminate the lamps
20
for (let [r, c] of lamps) {
21
if (lampCoord.has(`${r}-${c}`)) continue;
22
lampCoord.set(`${r}-${c}`);
23
rowHash[r] = rowHash[r] + 1 || 1;
24
colHash[c] = colHash[c] + 1 || 1;
25
leftDiag[r + c] = leftDiag[r + c] + 1 || 1;
26
rightDiag[c - r] = rightDiag[c - r] + 1 || 1;
27
}
28

29
// Second, query the lamps
30
let output = [];
31
for (let [row, col] of queries) query(row, col);
32
return output;
33

34
function query(row, col) {
35
if (
36
rowHash[row] ||
37
colHash[col] ||
38
leftDiag[row + col] ||
39
rightDiag[col - row]
40
) {
41
output.push(1);
42
// Check 8 adjacent cells
43
for (let [r, c] of directions) {
44
let newR = row + r,
45
newC = col + c;
46
if (newR < 0 || newC < 0 || newR >= n || newC >= n) continue;
47
// If the coordinate is a lamp, un-illuminate the lamp
48
if (lampCoord.has(`${newR}-${newC}`)) {
49
rowHash[newR]--,
50
colHash[newC]--,
51
leftDiag[newR + newC]--,
52
rightDiag[newC - newR]--;
53
lampCoord.delete(`${newR}-${newC}`);
54
}
55
}
56
} else output.push(0);
57
}
58
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0