[LeetCode] Queens That Can Attack the King

1222. Queens That Can Attack the King

On an 8x8 chessboard, there can be multiple Black Queens and one White King.

Given an array of integer coordinates queens that represents the positions of the Black Queens, and a pair of coordinates king that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {
vector<vector<int>> res;
int dx[8] = {-1,0,1,-1,1,-1,0,1}, dy[8] = {-1,-1,-1,0,0,1,1,1};
unordered_set<int> hash;
for(auto& q : queens) {
hash.insert((q[0]<<3) + q[1]);
}
for(int i = 0; i < 8; i++) {
int x = king[1] + dx[i], y = king[0] + dy[i];
while(0 <= x and x < 8 and 0 <= y and y < 8) {
if(hash.count((y << 3) + x)) {
res.push_back({y, x});
break;
}
x += dx[i];
y += dy[i];
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/01/PS/LeetCode/queens-that-can-attack-the-king/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.