aboutsummaryrefslogtreecommitdiff
path: root/2024/src
diff options
context:
space:
mode:
Diffstat (limited to '2024/src')
-rw-r--r--2024/src/day10.cpp92
1 files changed, 92 insertions, 0 deletions
diff --git a/2024/src/day10.cpp b/2024/src/day10.cpp
new file mode 100644
index 0000000..43dbd6e
--- /dev/null
+++ b/2024/src/day10.cpp
@@ -0,0 +1,92 @@
1#include <fstream>
2#include <iostream>
3#include <map>
4#include <queue>
5#include <set>
6#include <string>
7#include <tuple>
8#include <vector>
9using namespace std;
10
11using pos_type = tuple<size_t, size_t>;
12
13map<pos_type, int>
14read_file(string_view filename)
15{
16 fstream input{ filename };
17 map<pos_type, int> data;
18
19 size_t yPos = 0;
20 for ( string line; getline(input, line); ) {
21 for ( size_t xPos = 0; xPos != line.size(); ++xPos ) {
22 data[{ xPos, yPos }] = line.at(xPos) - '0';
23 }
24 ++yPos;
25 }
26 return data;
27}
28
29constexpr vector<pos_type>
30neighbors(pos_type pos)
31{
32 const auto [x, y] = pos;
33 return { { x - 1, y }, { x, y - 1 }, { x + 1, y }, { x, y + 1 } };
34}
35
36long
37bfs(const map<pos_type, int>& data, pos_type start_pos)
38{
39 long peaks = 0;
40
41 set<pos_type> seen;
42 queue<pos_type> queue;
43
44 queue.emplace(start_pos);
45 seen.emplace(start_pos);
46
47 while ( !queue.empty() ) {
48 auto pos = queue.front();
49 queue.pop();
50
51 if ( data.at(pos) == 9 ) {
52 ++peaks;
53 continue;
54 }
55
56 for ( const auto& neighbor: neighbors(pos) ) {
57 if ( !data.contains(neighbor) ||
58 seen.contains(neighbor) ||
59 data.at(neighbor) != data.at(pos) + 1 ) {
60 continue;
61 }
62
63 queue.emplace(neighbor);
64 seen.insert(neighbor);
65 }
66 }
67 return peaks;
68}
69
70void
71part1(const map<pos_type, int>& data)
72{
73 vector<pos_type> starts;
74 for ( const auto& [pos, value]: data ) {
75 if ( value == 0 ) {
76 starts.push_back(pos);
77 }
78 }
79
80 long sum = 0;
81 for ( const auto& start: starts ) {
82 sum += bfs(data, start);
83 }
84 cout << sum << endl;
85}
86
87int
88main()
89{
90 auto data = read_file("data/day10.txt");
91 part1(data);
92}