From aef729afe48cb5fe6728b9e9a8d4ff70259b8b7d Mon Sep 17 00:00:00 2001 From: Eric Mertens Date: Tue, 4 Apr 2023 07:23:11 -0700 Subject: [PATCH] simpler --- 2022/14.cpp | 74 +++++++++++++++++++++++++++++------------------------ 1 file changed, 41 insertions(+), 33 deletions(-) diff --git a/2022/14.cpp b/2022/14.cpp index b6fb0ef..8cdea52 100644 --- a/2022/14.cpp +++ b/2022/14.cpp @@ -5,7 +5,8 @@ #include #include #include -#include +#include +#include #include #include @@ -16,7 +17,6 @@ #include #include -#include namespace { @@ -97,32 +97,33 @@ auto FindBottom(Input const& input) -> std::int64_t return result; } -auto SearchOrder(std::set & world, aocpp::Coord here) -> aocpp::Generator -{ - co_yield aocpp::Down(here); - co_yield aocpp::Left(aocpp::Down(here)); - co_yield aocpp::Right(aocpp::Down(here)); - world.insert(here); -} +enum class Action { Visit, Mark }; auto Part1(std::int64_t bottom, std::set world) -> std::size_t { auto const starting_size = world.size(); + auto work = std::stack>{}; + work.emplace(Action::Visit, TOP); - auto path = std::vector>{}; - path.reserve(bottom - TOP.y); - path.push_back(SearchOrder(world, TOP)); - - while (!path.empty()) { - if (auto next = path.back()()) { - if (!world.contains(*next)) { - if (next->y == bottom) { - return world.size() - starting_size; + while (!work.empty()) { + auto const [action, here] = work.top(); + work.pop(); + + switch (action) { + case Action::Visit: + if (!world.contains(here)) { + if (here.y == bottom) { + return world.size() - starting_size; + } + work.emplace(Action::Mark, here); + work.emplace(Action::Visit, aocpp::Right(aocpp::Down(here))); + work.emplace(Action::Visit, aocpp::Left(aocpp::Down(here))); + work.emplace(Action::Visit, aocpp::Down(here)); } - path.push_back(SearchOrder(world, *next)); - } - } else { - path.pop_back(); + break; + case Action::Mark: + world.insert(here); + break; } } @@ -132,18 +133,25 @@ auto Part1(std::int64_t bottom, std::set world) -> std::size_t auto Part2(std::int64_t bottom, std::set world) -> std::size_t { auto const starting_size = world.size(); - - auto path = std::vector>{}; - path.reserve(2 + bottom - TOP.y); - path.push_back(SearchOrder(world, TOP)); + auto work = std::stack>{}; + work.emplace(Action::Visit, TOP); - while (!path.empty()) { - if (auto next = path.back()()) { - if (next->y - 2 != bottom && !world.contains(*next)) { - path.push_back(SearchOrder(world, *next)); - } - } else { - path.pop_back(); + while (!work.empty()) { + auto const [action, here] = work.top(); + work.pop(); + + switch (action) { + case Action::Visit: + if (here.y - 2 != bottom && !world.contains(here)) { + work.emplace(Action::Mark, here); + work.emplace(Action::Visit, aocpp::Right(aocpp::Down(here))); + work.emplace(Action::Visit, aocpp::Left(aocpp::Down(here))); + work.emplace(Action::Visit, aocpp::Down(here)); + } + break; + case Action::Mark: + world.insert(here); + break; } }