aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/day21.cpp97
1 files changed, 97 insertions, 0 deletions
diff --git a/src/day21.cpp b/src/day21.cpp
new file mode 100644
index 0000000..91611c5
--- /dev/null
+++ b/src/day21.cpp
@@ -0,0 +1,97 @@
1#include <cstddef>
2#include <fstream>
3#include <iostream>
4#include <queue>
5#include <set>
6#include <string>
7#include <vector>
8using namespace std;
9
10using position = tuple<size_t, size_t>;
11
12vector<string>
13read_file(string_view filename)
14{
15 fstream input{ filename };
16 vector<string> data;
17
18 for ( string line; getline(input, line); ) {
19 data.emplace_back(line);
20 }
21
22 return data;
23}
24
25position
26find_start_position(const vector<string>& lines)
27{
28 for ( size_t row = 0; row != lines.size(); ++row ) {
29 for ( size_t col = 0; col != lines[row].size(); ++col ) {
30 if ( lines[row][col] == 'S' ) {
31 return { row, col };
32 }
33 }
34 }
35 return {};
36}
37
38set<position>
39find_neighbours(position pos, const vector<string>& lines)
40{
41 static const vector<position> movements = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };
42
43 set<position> neighbours;
44 const auto [row, col] = pos;
45
46 for ( const auto& [drow, dcol]: movements ) {
47 const auto nrow = row + drow;
48 const auto ncol = col + dcol;
49
50 if ( nrow < lines.size() && ncol < lines[0].size() && lines[nrow][ncol] == '.' ) {
51 neighbours.emplace(nrow, ncol);
52 }
53 }
54
55 return neighbours;
56}
57
58void
59part1()
60{
61 auto lines = read_file("data/day21.txt");
62 auto start_position = find_start_position(lines);
63
64 queue<position> positions;
65 positions.emplace(start_position);
66
67 long sum = 0;
68 for ( int round = 0; round != 64; ++round ) {
69 set<position> next_positions;
70
71 sum = 0;
72 while ( !positions.empty() ) {
73 const auto [curr_row, curr_col] = positions.front();
74 lines[curr_row][curr_col] = '.';
75
76 auto neighbours = find_neighbours(positions.front(), lines);
77 positions.pop();
78
79 for ( const auto& [row, col]: neighbours ) {
80 lines[row][col] = 'O';
81 next_positions.emplace(row, col);
82 ++sum;
83 }
84 }
85
86 for ( const auto& position: next_positions ) {
87 positions.emplace(position);
88 }
89 }
90 cout << sum << endl;
91}
92
93int
94main()
95{
96 part1();
97}