forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
walking-robot-simulation.cpp
44 lines (42 loc) · 1.48 KB
/
walking-robot-simulation.cpp
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
// Time: O(n + k)
// Space: O(k)
class Solution {
private:
template <typename T>
struct PairHash {
size_t operator()(const pair<T, T>& p) const {
size_t seed = 0;
seed ^= std::hash<T>{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2);
seed ^= std::hash<T>{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2);
return seed;
}
};
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
static const vector<pair<int, int>> directions{{0, 1}, {1, 0},
{0, -1}, {-1, 0}};
unordered_set<pair<int, int>, PairHash<int>> lookup;
for (const auto& obstacle: obstacles) {
lookup.emplace(obstacle[0], obstacle[1]);
}
int result = 0;
int x = 0, y = 0, i = 0;
for (const auto& cmd: commands) {
if (cmd == -2) {
i = (i - 1 + 4) % 4;
} else if (cmd == -1) {
i = (i + 1) % 4;
} else {
for (int k = 0; k < cmd; ++k) {
if (!lookup.count(make_pair(x + directions[i].first,
y + directions[i].second))) {
x += directions[i].first;
y += directions[i].second;
result = max(result, x * x + y * y);
}
}
}
}
return result;
}
};