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