From 9fe5babb3395f4a9ed27d40a7c28e349a0eaa32d Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 22 Apr 2024 23:57:10 +0200 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB752.=20Open=20the=20Lock?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/open-the-lock.cpp | 53 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 cpp/open-the-lock.cpp diff --git a/cpp/open-the-lock.cpp b/cpp/open-the-lock.cpp new file mode 100644 index 0000000..88c2d82 --- /dev/null +++ b/cpp/open-the-lock.cpp @@ -0,0 +1,53 @@ +#include +#include +#include + +class Solution { + public: + int openLock(const std::vector &deadends, + const std::string &target) { + std::vector visited(10000); + for (const auto &end : deadends) { + visited[std::stoi(end)] = true; + } + + // we're already starting with a dead end + if (visited[0]) { + return -1; + } + + auto t = std::stoi(target); + + std::queue> q; + q.emplace(0, 0); + visited[0] = true; + + while (!q.empty()) { + auto [steps, comb] = q.front(); + q.pop(); + + // found the target + if (comb == t) { + return steps; + } + + auto comb_tmp = comb; + for (auto d = 1; d < 10000; d *= 10) { + auto digit = comb_tmp % 10; + comb_tmp /= 10; + + for (auto i : {-1, 1}) { + auto next_digit = (digit + i + 10) % 10; + auto next_comb = comb + (next_digit - digit) * d; + + if (!visited[next_comb]) { + q.emplace(steps + 1, next_comb); + visited[next_comb] = true; + } + } + } + } + + return -1; + } +};