aboutsummaryrefslogtreecommitdiff
path: root/2017/src/day12.cpp
diff options
context:
space:
mode:
Diffstat (limited to '2017/src/day12.cpp')
-rw-r--r--2017/src/day12.cpp115
1 files changed, 115 insertions, 0 deletions
diff --git a/2017/src/day12.cpp b/2017/src/day12.cpp
new file mode 100644
index 0000000..66bf186
--- /dev/null
+++ b/2017/src/day12.cpp
@@ -0,0 +1,115 @@
1#include <filesystem>
2#include <fstream>
3#include <iostream>
4#include <map>
5#include <queue>
6#include <set>
7#include <string>
8#include <vector>
9
10using namespace std;
11
12namespace {
13
14using graph_type = map<int, set<int>>;
15
16vector<int>
17split_to_int(const string& line, const string& delimiters)
18{
19 vector<int> result;
20
21 size_t start = 0;
22 size_t end = 0;
23
24 while ( (end = line.find_first_of(delimiters, start)) != string::npos ) {
25 if ( end != start ) {
26 result.emplace_back(stoi(line.substr(start, end - start)));
27 }
28
29 start = end + 1;
30 }
31
32 if ( start != line.size() ) {
33 result.emplace_back(stoi(line.substr(start)));
34 }
35
36 return result;
37}
38
39graph_type
40read_lines(const filesystem::path& filename)
41{
42 ifstream file{ filename };
43 graph_type result;
44
45 for ( string line; getline(file, line); ) {
46 auto parts = split_to_int(line, "<-> ,");
47
48 for ( size_t i = 1; i < parts.size(); ++i ) {
49 result[parts[0]].insert(parts[i]);
50 result[parts[i]].insert(parts[0]);
51 }
52 }
53
54 return result;
55}
56
57void
58bfs_mark(const graph_type& graph, int start, set<int>& seen)
59{
60 queue<int> queue;
61
62 queue.emplace(start);
63 seen.emplace(start);
64
65 while ( !queue.empty() ) {
66 int prg = queue.front();
67 queue.pop();
68
69 for ( auto link: graph.at(prg) ) {
70 if ( !seen.contains(link) ) {
71 queue.emplace(link);
72 seen.emplace(link);
73 }
74 }
75 }
76}
77
78void
79part1(const graph_type& graph)
80{
81 set<int> seen;
82
83 bfs_mark(graph, 0, seen);
84
85 cout << "Part1: " << seen.size() << '\n';
86}
87
88void
89part2(const graph_type& graph)
90{
91 set<int> seen;
92
93 int count = 0;
94
95 for ( const auto& [i, _]: graph ) {
96 if ( seen.contains(i) ) {
97 continue;
98 }
99
100 ++count;
101
102 bfs_mark(graph, i, seen);
103 }
104 cout << "Part2: " << count << '\n';
105}
106
107} // namespace
108
109int
110main()
111{
112 auto data = read_lines("data/day12.txt");
113 part1(data);
114 part2(data);
115}