Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
open-the-lock.cpp 1.32 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-12-24 23:15 +08:00 . Create open-the-lock.cpp
// Time: O(k * n^k + d), n is the number of alphabets,
// k is the length of target,
// d is the size of deadends
// Space: O(k * n^k + d)
class Solution {
public:
int openLock(vector<string>& deadends, string target) {
unordered_set<string> dead(deadends.begin(), deadends.end());
vector<string> q{"0000"};
unordered_set<string> lookup{"0000"};
int depth = 0;
while (!q.empty()) {
vector<string> next_q;
for (const auto& node : q) {
if (node == target) {
return depth;
}
if (dead.count(node)) {
continue;
}
for (int i = 0; i < 4; ++i) {
auto n = node[i] - '0';
for (const auto& d : {-1, 1}) {
auto nn = (n + d + 10) % 10;
auto neighbor = node;
neighbor[i] = '0' + nn;
if (!lookup.count(neighbor)) {
lookup.emplace(neighbor);
next_q.emplace_back(neighbor);
}
}
}
}
swap(q, next_q);
++depth;
}
return -1;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助