Skip to content

Commit ccc36ea

Browse files
authored
Create queens-that-can-attack-the-king.cpp
1 parent c7a70c8 commit ccc36ea

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Time: O(1)
2+
// Space: O(1)
3+
4+
class Solution {
5+
private:
6+
template <typename T>
7+
struct PairHash {
8+
size_t operator()(const pair<T, T>& p) const {
9+
size_t seed = 0;
10+
seed ^= std::hash<T>{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2);
11+
seed ^= std::hash<T>{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2);
12+
return seed;
13+
}
14+
};
15+
16+
public:
17+
vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {
18+
static const vector<pair<int, int>> directions =
19+
{{-1, 0}, {0, 1}, {1, 0}, {0, -1},
20+
{-1, 1}, {1, 1}, {1, -1}, {-1, -1}};
21+
vector<vector<int>> result;
22+
unordered_set<pair<int, int>, PairHash<int>> lookup;
23+
for (const auto& queen : queens) {
24+
lookup.emplace(queen[0], queen[1]);
25+
}
26+
for (const auto& [dx, dy] : directions) {
27+
for (int i = 1; i <= 7; ++i) {
28+
int x = king[0] + dx * i;
29+
int y = king[1] + dy * i;
30+
if (lookup.count(make_pair(x, y))) {
31+
result.push_back({x, y});
32+
break;
33+
}
34+
}
35+
}
36+
return result;
37+
}
38+
};

0 commit comments

Comments
 (0)