From ccc1995cb89107e7c8ba5795346f93ea16a959e7 Mon Sep 17 00:00:00 2001 From: hladu357 Date: Sat, 18 May 2024 13:27:21 +0200 Subject: [PATCH] lock --- lock.cpp | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 lock.cpp diff --git a/lock.cpp b/lock.cpp new file mode 100644 index 0000000..f2dc7a2 --- /dev/null +++ b/lock.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include + +class Solution { +public: + union u { + public: + char c[4]; + int i; + }; + + int openLock(std::vector& deadends, std::string target) { + std::unordered_set e; + std::queue> q; + + u t; + u b; + b.i = 0; + for (int i = 0; i < 4; ++i) { + t.c[i] = static_cast(target[i] - '0'); + } + for (const auto& i : deadends) { + if (target == i || target == "0000") return -1; + + u tmp; + for (int j = 0; j < 4; ++j) { + tmp.c[j] = static_cast(i[j] - '0'); + } + e.insert(tmp.i); + } + + + + e.insert(0); + q.emplace(b,0); + + while(q.size()) { + auto i = q.front(); + q.pop(); + if (i.first.i == t.i) return i.second; + + for (int j = 0; j < 4; ++j) { + u w = i.first; + ++w.c[j] %= 10; + auto it = e.emplace(w.i); + if (it.second) { + q.emplace(w, i.second + 1); + } + } + + for (int j = 0; j < 4; ++j) { + u w = i.first; + if (!w.c[j]--) w.c[j] = 9; + auto it = e.emplace(w.i); + if (it.second) { + q.emplace(w, i.second + 1); + } + } + } + return -1; + } +}; + +int main() { + Solution s; + std::vector v = {"8888"}; + std::cout << s.openLock(v, "0009"); + return 0; +} \ No newline at end of file