Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
walking-robot-simulation.cpp 1.48 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-07-24 22:48 +08:00 . Create walking-robot-simulation.cpp
// 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;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助