11#include < stack>
2- #include " ../aoclib/aocio.hpp"
3- #include " ../aoclib/grid.hpp"
4- #include " ../aoclib/vec.hpp"
2+ #include < numeric>
3+ #include " aoclib/aocio.hpp"
4+ #include " aoclib/grid.hpp"
5+ #include " aoclib/vec.hpp"
56
67/*
78 Problem: https://adventofcode.com/2024/day/10
@@ -23,13 +24,14 @@ using Vec2 = aocutil::Vec2<int>;
2324int part_one (const std::vector<std::string>& lines, bool part_two = false )
2425{
2526 Grid<int > height_map;
26- for (const auto & line : lines) {
27- std::vector<int > row;
27+
28+ for (const auto & line : lines) {
29+ std::vector<decltype (height_map)::value_type> row;
2830 std::transform (line.cbegin (), line.cend (), std::back_inserter (row), [](char c) {
2931 return aocio::parse_digit (c).value ();
3032 });
3133 height_map.push_row (row);
32- }
34+ }
3335
3436 const auto get_adjacent = [&height_map = std::as_const (height_map)](const Vec2& pos) {
3537 const auto dirs = aocutil::all_dirs_vec2<int >();
@@ -42,21 +44,19 @@ int part_one(const std::vector<std::string>& lines, bool part_two = false)
4244 return neighbors;
4345 };
4446
45- int result = 0 ;
46- const std::vector<Vec2> trailheads = height_map.find_elem_positions_if ([](int h) {return h == 0 ;});
47- for (const auto & trailhead : trailheads) {
48- int score = 0 ;
47+ const auto trailhead_score = [&height_map = std::as_const (height_map), &get_adjacent, part_two](const Vec2& trailhead) -> int {
48+ int score = 0 ;
4949 std::stack<Vec2> positions;
5050 positions.push (trailhead);
5151 Grid<bool > reached (height_map.width (), height_map.height (), false );
5252
5353 while (!positions.empty ()) { // Depth-first search.
5454 const Vec2 pos = positions.top ();
5555 positions.pop ();
56- const int current_height = height_map.get (pos);
56+ const auto current_height = height_map.get (pos);
5757 std::vector<Vec2> adjacent = get_adjacent (pos);
5858 for (const auto & adj_pos : adjacent) {
59- int neighbor_height = height_map.get (adj_pos);
59+ const auto neighbor_height = height_map.get (adj_pos);
6060 if (neighbor_height == current_height + 1 ) {
6161 if (neighbor_height == 9 && !reached.get (adj_pos)) {
6262 reached.set (adj_pos, !part_two); // Only use the "reached" grid for Part 1 (i.e. count all paths for Part 2)
@@ -67,9 +67,11 @@ int part_one(const std::vector<std::string>& lines, bool part_two = false)
6767 }
6868 }
6969 }
70- result += score;
71- }
72- return result;
70+ return score;
71+ };
72+
73+ const std::vector<Vec2> trailheads = height_map.find_elem_positions_if ([](auto h) {return h == 0 ;});
74+ return std::transform_reduce (trailheads.cbegin (), trailheads.cend (), int {0 }, std::plus{}, trailhead_score);
7375}
7476
7577int part_two (const std::vector<std::string>& lines)
0 commit comments