[Hacker Rank] Queen's Attack II

Queen’s Attack II

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
int directionAt(int y, int x, int oy, int ox) {
int dy = oy - y, dx = ox - x;
if(dy == 0) return dx > 0 ? 3 : 7;
if(dx == 0) return dy > 0 ? 1 : 5;
if(abs(dy) != abs(dx)) return -1;
if(dy > 0 and dx > 0) return 2;
if(dy > 0 and dx < 0) return 0;
if(dy < 0 and dx > 0) return 4;
if(dy < 0 and dx < 0) return 6;

return -1;
}
int queensAttack(int n, int k, int y, int x, vector<vector<int>> obstacles) {
int res[8] = {}, l = x - 1, r = n - x, u = n - y, b = y - 1;

res[0] = min(l, u);
res[1] = u;
res[2] = min(r, u);
res[3] = r;
res[4] = min(r, b);
res[5] = b;
res[6] = min(l, b);
res[7] = l;

for(auto& o : obstacles) {
auto d = directionAt(y, x, o[0], o[1]);
if(d == -1) continue;
if(d & 1) {
int dis = max(abs(o[0] - y), abs(o[1] - x)) - 1;
res[d] = min(res[d], dis);
} else {
int dis = max(abs(o[0] - y), abs(o[1] - x)) - 1;
res[d] = min(res[d], dis);
}
}

return accumulate(begin(res), end(res), 0);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/04/PS/HackerRank/queens-attack-2/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.