aocpp/2022/12.cpp
2023-03-22 14:02:29 -07:00

86 lines
2.0 KiB
C++

#include <cstdint>
#include <iostream>
#include <optional>
#include <set>
#include <sstream>
#include <tuple>
#include <vector>
#include <doctest.h>
#include <aocpp/Coord.hpp>
#include <aocpp/Grid.hpp>
#include <aocpp/Startup.hpp>
using aocpp::Coord;
using aocpp::Grid;
namespace {
auto Parse(std::istream & in) -> std::tuple<Coord, std::vector<Coord>, Coord, Grid>
{
Coord start1 {};
std::vector<Coord> starts2;
Coord end {};
auto grid = Grid::Parse(in);
grid.each([&](Coord c, char v) {
switch (v) {
case 'S': grid[c] = 'a'; start1 = c; break;
case 'E': grid[c] = 'z'; end = c; break;
case 'a': starts2.push_back(c); break;
}
});
return {start1, std::move(starts2), end, std::move(grid)};
}
auto Solve(std::vector<Coord> starts, Coord end, Grid const& grid) -> std::optional<std::int64_t>
{
std::vector<Coord> next_layer;
std::set<Coord> seen;
std::int64_t counter {1};
while (!starts.empty()) {
for (auto here : starts) {
if (!seen.insert(here).second) continue;
auto here_height = grid[here];
for (auto next : {Up(here), Down(here), Left(here), Right(here)}) {
if (!grid.contains(next)) continue;
if (grid[next] - 1 > here_height) continue;
if (next == end) { return counter; }
next_layer.push_back(next);
}
}
counter++;
starts.clear();
std::swap(starts, next_layer);
}
return {};
}
} // namespace
TEST_SUITE("2022-12 examples") {
TEST_CASE("documented example") {
std::istringstream in {
"Sabqponm\n"
"abcryxxl\n"
"accszExk\n"
"acctuvwj\n"
"abdefghi\n"
};
auto [start1, starts2, end, grid] = Parse(in);
CHECK(31 == Solve({start1}, end, grid));
CHECK(29 == Solve(std::move(starts2), end, grid));
}
}
auto Main(std::istream & in, std::ostream & out) -> void
{
auto [start1, starts2, end, grid] = Parse(in);
out << "Part 1: " << Solve({start1}, end, grid).value_or(-1) << std::endl;
out << "Part 2: " << Solve(std::move(starts2), end, grid).value_or(-1) << std::endl;
}