[LeetCode] Grid Illumination

1001. Grid Illumination

There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off.

You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on.

When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.

You are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj].

Return an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not.

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
struct pair_hash
{
template <class T1, class T2>
std::size_t operator() (const std::pair<T1, T2> &pair) const {
return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
}
};
class Solution {
unordered_map<int, unordered_set<pair<int,int>, pair_hash>> R, C, D, RD;
int getRK(pair<int,int> p) {
return p.first;
}
int getCK(pair<int,int> p) {
return p.second;
}
int getDK(pair<int,int> p) {
return p.first - p.second;
}
int getRDK(pair<int,int> p) {
return p.first + p.second;
}
void insert(pair<int,int> l) {
R[getRK(l)].insert(l);
C[getCK(l)].insert(l);
D[getDK(l)].insert(l);
RD[getRDK(l)].insert(l);
}
bool qry(pair<int,int> l) {
return !R[getRK(l)].empty() or !C[getCK(l)].empty() or !D[getDK(l)].empty() or !RD[getRDK(l)].empty();
}
void _remove(pair<int,int> l) {
R[getRK(l)].erase(l);
C[getCK(l)].erase(l);
D[getDK(l)].erase(l);
RD[getRDK(l)].erase(l);
}
void remove(vector<int> l) {
for(int i = -1; i <= 1; i++) {
for(int j = -1; j <= 1; j++) {
_remove(make_pair(l[0] + i, l[1] + j));
}
}
}
public:
vector<int> gridIllumination(int n, vector<vector<int>>& lamps, vector<vector<int>>& queries) {
int q = queries.size();
vector<int> res(q);
for(auto& l : lamps)
insert({l[0],l[1]});
for(int i = 0; i < q; i++) {
res[i] = qry({queries[i][0], queries[i][1]});
remove(queries[i]);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/02/PS/LeetCode/grid-illumination/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.