Skip to content

Commit e689650

Browse files
authored
Create walking-robot-simulation.cpp
1 parent ce1dd76 commit e689650

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

C++/walking-robot-simulation.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Time: O(n + k)
2+
// Space: O(k)
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+
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
18+
static const vector<pair<int, int>> directions{{0, 1}, {1, 0},
19+
{0, -1}, {-1, 0}};
20+
unordered_set<pair<int, int>, PairHash<int>> lookup;
21+
for (const auto& obstacle: obstacles) {
22+
lookup.emplace(obstacle[0], obstacle[1]);
23+
}
24+
int result = 0;
25+
int x = 0, y = 0, i = 0;
26+
for (const auto& cmd: commands) {
27+
if (cmd == -2) {
28+
i = (i - 1 + 4) % 4;
29+
} else if (cmd == -1) {
30+
i = (i + 1) % 4;
31+
} else {
32+
for (int k = 0; k < cmd; ++k) {
33+
if (!lookup.count(make_pair(x + directions[i].first,
34+
y + directions[i].second))) {
35+
x += directions[i].first;
36+
y += directions[i].second;
37+
result = max(result, x * x + y * y);
38+
}
39+
}
40+
}
41+
}
42+
return result;
43+
}
44+
};

0 commit comments

Comments
 (0)