diff --git a/2022/12.cpp b/2022/12.cpp index 6ac570a..37a0aa0 100644 --- a/2022/12.cpp +++ b/2022/12.cpp @@ -19,10 +19,13 @@ namespace { auto Parse(std::istream & in) -> std::tuple, Coord, Grid> { - Coord start1 {}; - std::vector starts2; - Coord end {}; - auto grid = Grid::Parse(in); + std::tuple, Coord, Grid> result {{},{},{},Grid::Parse(in)}; + // I'd use a structured binding here, but not all current compilers + // supports capture of the resulting bindings in the lambda below + auto& start1 = std::get<0>(result); + auto& starts2 = std::get<1>(result); + auto& end = std::get<2>(result); + auto& grid = std::get<3>(result); grid.each([&](Coord c, char v) { switch (v) { @@ -32,29 +35,28 @@ auto Parse(std::istream & in) -> std::tuple, Coord, Gr } }); - return {start1, std::move(starts2), end, std::move(grid)}; + return result; } auto Solve(std::vector starts, Coord end, Grid const& grid) -> std::optional { std::vector next_layer; std::set seen; - std::int64_t counter {1}; + std::int64_t counter {}; while (!starts.empty()) { - for (auto here : starts) { + counter++; + for (auto const& 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); + for (auto const next : {Up(here), Down(here), Left(here), Right(here)}) { + if (grid.contains(next) && grid[next] <= grid[here] + 1) { + if (next == end) { return counter; } + next_layer.push_back(next); + } } } - counter++; - starts.clear(); std::swap(starts, next_layer); + next_layer.clear(); } return {};