aboutsummaryrefslogtreecommitdiff
path: root/2024
diff options
context:
space:
mode:
Diffstat (limited to '2024')
-rw-r--r--2024/src/day18.cpp75
1 files changed, 75 insertions, 0 deletions
diff --git a/2024/src/day18.cpp b/2024/src/day18.cpp
new file mode 100644
index 0000000..fedd836
--- /dev/null
+++ b/2024/src/day18.cpp
@@ -0,0 +1,75 @@
1#include <fstream>
2#include <iostream>
3#include <queue>
4#include <set>
5#include <sstream>
6#include <string>
7#include <tuple>
8#include <vector>
9using namespace std;
10
11using pos_type = tuple<long, long>;
12
13vector<pos_type>
14read_file(string_view filename)
15{
16 fstream input{ filename };
17 vector<pos_type> data;
18
19 long lhs = 0;
20 long rhs = 0;
21 char chr = 0;
22
23 while ( input >> lhs >> chr >> rhs ) {
24 data.emplace_back(lhs, rhs);
25 }
26 return data;
27}
28
29void
30part1(const vector<pos_type>& data, long size)
31{
32 set<pos_type> stones{ data.begin(), data.end() };
33
34 set<pos_type> seen;
35
36 // x, y, distance
37 queue<tuple<pos_type, long>> queue;
38 queue.push({ { 0, 0 }, 0 });
39
40 while ( !queue.empty() ) {
41 const auto& [pos, distance] = queue.front();
42 queue.pop();
43
44 const auto [x, y] = pos;
45
46 if ( x == size && y == size ) {
47 cout << distance << endl;
48 return;
49 }
50
51 if ( x < 0 || y < 0 || x > size || y > size ) {
52 continue;
53 }
54
55 if ( stones.contains(pos) ) {
56 continue;
57 }
58
59 if ( seen.contains(pos) ) {
60 continue;
61 }
62 seen.insert(pos);
63
64 for ( const auto& [nx, ny]: vector<pos_type>{ { x - 1, y }, { x + 1, y }, { x, y - 1 }, { x, y + 1 } } ) {
65 queue.push({ { nx, ny }, distance + 1 });
66 }
67 }
68}
69
70int
71main()
72{
73 const auto data = read_file("data/day18.txt");
74 part1({ data.begin(), data.begin() + 1024 }, 70);
75}