aboutsummaryrefslogtreecommitdiff
path: root/2024/src/day10.cpp
blob: 58b797f11a14e7594d4813582df97d8bc28bf135 (plain)
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include <fstream>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <tuple>
#include <vector>
using namespace std;

using pos_type = tuple<size_t, size_t>;

map<pos_type, int>
read_file(string_view filename)
{
	fstream            input{ filename };
	map<pos_type, int> data;

	size_t yPos = 0;
	for ( string line; getline(input, line); ) {
		for ( size_t xPos = 0; xPos != line.size(); ++xPos ) {
			data[{ xPos, yPos }] = line.at(xPos) - '0';
		}
		++yPos;
	}
	return data;
}

constexpr vector<pos_type>
neighbors(pos_type pos)
{
	const auto [x, y] = pos;
	return { { x - 1, y }, { x, y - 1 }, { x + 1, y }, { x, y + 1 } };
}

size_t
bfs(const map<pos_type, int>& data, pos_type start_pos)
{
	size_t peaks = 0;

	set<pos_type>   seen;
	queue<pos_type> queue;

	queue.emplace(start_pos);
	seen.emplace(start_pos);

	while ( !queue.empty() ) {
		auto pos = queue.front();
		queue.pop();

		if ( data.at(pos) == 9 ) {
			++peaks;
			continue;
		}

		for ( const auto& neighbor: neighbors(pos) ) {
			if ( !data.contains(neighbor) ||
			     seen.contains(neighbor) ||
			     data.at(neighbor) != data.at(pos) + 1 ) {
				continue;
			}

			queue.emplace(neighbor);
			seen.insert(neighbor);
		}
	}
	return peaks;
}

void
part1(const map<pos_type, int>& data)
{
	vector<pos_type> starts;
	for ( const auto& [pos, value]: data ) {
		if ( value == 0 ) {
			starts.push_back(pos);
		}
	}

	size_t sum = 0;
	for ( const auto& start: starts ) {
		sum += bfs(data, start);
	}
	cout << sum << endl;
}

size_t
bfs2(const map<pos_type, int>& data, pos_type start_pos)
{
	size_t paths = 0;

	queue<pos_type> queue;

	queue.push(start_pos);

	while ( !queue.empty() ) {
		auto pos = queue.front();
		queue.pop();

		if ( data.at(pos) == 9 ) {
			++paths;
			continue;
		}

		for ( const auto& neighbor: neighbors(pos) ) {
			if ( !data.contains(neighbor) ||
			     data.at(neighbor) != data.at(pos) + 1 ) {
				continue;
			}

			queue.emplace(neighbor);
		}
	}
	return paths;
}

void
part2(const map<pos_type, int>& data)
{
	vector<pos_type> starts;
	for ( const auto& [pos, value]: data ) {
		if ( value == 0 ) {
			starts.push_back(pos);
		}
	}

	size_t sum = 0;
	for ( const auto& start: starts ) {
		sum += bfs2(data, start);
	}
	cout << sum << endl;
}

int
main()
{
	auto data = read_file("data/day10.txt");
	part1(data);
	part2(data);
}