1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
minimum-jumps-to-reach-home.cpp 1.45 KB
一键复制 编辑 原始数据 按行查看 历史
// Time: O(max(x, max(forbidden)) + a + (b+a))
// Space: O(max(x, max(forbidden)) + a + (b+a))
class Solution {
public:
int minimumJumps(vector<int>& forbidden, int a, int b, int x) {
int max_f = *max_element(cbegin(forbidden), cend(forbidden));
int max_val = (a >= b) ? x + b : max(x, max_f) + a + b; // a may be a non-periodic area, (a+b) is a periodic area which is divided by gcd(a, b) and all points are reachable
vector<unordered_set<int>> lookup(2);
for (const auto& pos : forbidden) {
lookup[0].emplace(pos);
lookup[1].emplace(pos);
}
int result = 0;
vector<pair<int, int>> q = {{0, true}};
lookup[0].emplace(0);
while (!empty(q)) {
vector<pair<int, int>> new_q;
for (const auto& [pos, can_back] : q) {
if (pos == x) {
return result;
}
if (pos + a <= max_val && !lookup[0].count(pos + a)) {
lookup[0].emplace(pos + a);
new_q.emplace_back(pos + a, true);
}
if (!can_back) {
continue;
}
if (pos - b >= 0 && !lookup[1].count(pos - b)) {
lookup[1].emplace(pos - b);
new_q.emplace_back(pos - b, false);
}
}
q = move(new_q);
++result;
}
return -1;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助