2024 / Day 16
Reindeer Maze
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* The local input is 20022 bytes, 141 lines, longest line 141. The maze is 141
4 * by 141. SIDE = 160 bounds four orientation states per cell. Use indexed-heap
5 * Dijkstra with independent 1000-cost rotations and 1-cost forward steps,
6 * including a turn in place in a dead end. Reverse Dijkstra starts at every end
7 * orientation; a tile belongs to an optimal route when forward plus reverse
8 * distance equals the optimum. */
9
10static slice line(slice s, size_t *p) {
11 size_t b = *p;
12 while (*p < s.l && s.p[*p] != '\n') {
13 (*p)++;
14 }
15 size_t e = *p;
16 if (*p < s.l) {
17 (*p)++;
18 }
19 if (e > b && s.p[e - 1] == '\r') {
20 e--;
21 }
22 return (slice){s.p + b, e - b};
23}
24
25enum { SIDE = 160, STATES = SIDE * SIDE * 4 };
26
27static uint8_t map[SIDE][SIDE];
28static int32_t forward[STATES], backward[STATES], heap[STATES],
29 positions[STATES];
30static int32_t *dist;
31static int32_t hn, w, h;
32static const int32_t dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
33
34static void swap(int32_t a, int32_t b) {
35 int32_t v = heap[a];
36 heap[a] = heap[b];
37 heap[b] = v;
38 positions[heap[a]] = a;
39 positions[heap[b]] = b;
40}
41
42static void offer(int32_t id, int32_t value) {
43 if (value >= dist[id]) {
44 return;
45 }
46 dist[id] = value;
47 int32_t k = positions[id];
48 if (k < 0) {
49 aoc_assert(hn < STATES, "maze heap exceeds orientation state bound");
50 k = hn++;
51 heap[k] = id;
52 positions[id] = k;
53 }
54 while (k && dist[heap[k]] < dist[heap[(k - 1) / 2]]) {
55 swap(k, (k - 1) / 2);
56 k = (k - 1) / 2;
57 }
58}
59
60static int32_t pop(void) {
61 int32_t id = heap[0];
62 hn--;
63 if (hn) {
64 heap[0] = heap[hn];
65 positions[heap[0]] = 0;
66 int32_t k = 0;
67 while (2 * k + 1 < hn) {
68 int32_t c = 2 * k + 1;
69 if (c + 1 < hn && dist[heap[c + 1]] < dist[heap[c]]) {
70 c++;
71 }
72 if (dist[heap[k]] <= dist[heap[c]]) {
73 break;
74 }
75 swap(k, c);
76 k = c;
77 }
78 }
79 positions[id] = -1;
80 return id;
81}
82
83static void dijkstra(int32_t *table, int32_t source, int32_t reverse) {
84 dist = table;
85 hn = 0;
86 for (int32_t i = 0; i < w * h * 4; i++) {
87 dist[i] = INT32_MAX;
88 positions[i] = -1;
89 }
90 for (int32_t d = 0; d < (reverse ? 4 : 1); d++) {
91 offer(source * 4 + d, 0);
92 }
93 while (hn) {
94 int32_t id = pop(), dir = id % 4, x = id / 4 % w, y = id / 4 / w,
95 value = dist[id];
96 offer((id / 4) * 4 + (dir + 1) % 4, value + 1000);
97 offer((id / 4) * 4 + (dir + 3) % 4, value + 1000);
98 int32_t xx = x + (reverse ? -dx[dir] : dx[dir]),
99 yy = y + (reverse ? -dy[dir] : dy[dir]);
100 if (xx >= 0 && xx < w && yy >= 0 && yy < h && map[yy][xx] != '#') {
101 offer((yy * w + xx) * 4 + dir, value + 1);
102 }
103 }
104}
105
106static inline __attribute__((always_inline)) void
107read_reindeer_maze_row(int32_t *start_ref, int32_t *end_ref, slice l) {
108 for (int32_t x = 0; x < w; x++) {
109 uint8_t c = l.p[x];
110 aoc_assert(c == '#' || c == '.' || c == 'S' || c == 'E',
111 "bad reindeer maze cell");
112 if (c == 'S') {
113 aoc_assert((*start_ref) < 0, "multiple maze starts");
114 (*start_ref) = h * w + x;
115 }
116 if (c == 'E') {
117 aoc_assert((*end_ref) < 0, "multiple maze ends");
118 (*end_ref) = h * w + x;
119 }
120 map[h][x] = c;
121 }
122}
123
124static inline __attribute__((always_inline)) int32_t
125check_optimal_headings(int32_t best, int32_t total, int32_t cell) {
126 for (int32_t d = 0; d < 4; d++) {
127 int32_t id = cell * 4 + d;
128 if (forward[id] != INT32_MAX && backward[id] != INT32_MAX &&
129 (int64_t)forward[id] + backward[id] == best) {
130 total++;
131 break;
132 }
133 }
134
135 return total;
136}
137
138static slice solve(slice s, int32_t part) {
139 size_t p = 0;
140 int32_t start = -1, end = -1;
141 w = h = 0;
142 while (p < s.l) {
143 slice l = line(s, &p);
144 aoc_assert(h < SIDE && l.l && l.l <= SIDE,
145 "reindeer maze exceeds 160 by 160");
146 if (!h) {
147 w = l.l;
148 }
149 aoc_assert(l.l == (size_t)w, "ragged reindeer maze");
150 read_reindeer_maze_row(&start, &end, l);
151 h++;
152 }
153 aoc_assert(start >= 0 && end >= 0, "missing maze start or end");
154 dijkstra(forward, start, 0);
155 int32_t best = INT32_MAX;
156 for (int32_t d = 0; d < 4; d++) {
157 if (forward[end * 4 + d] < best) {
158 best = forward[end * 4 + d];
159 }
160 }
161 aoc_assert(best != INT32_MAX, "no reindeer route");
162 if (part == 1) {
163 return slice_from_i64(best);
164 }
165 dijkstra(backward, end, 1);
166 int32_t total = 0;
167 for (int32_t cell = 0; cell < w * h; cell++) {
168 total = check_optimal_headings(best, total, cell);
169 }
170 return slice_from_i64(total);
171}
172
173slice part1(slice s) {
174 return solve(s, 1);
175}
176
177slice part2(slice s) {
178 return solve(s, 2);
179}
180
181const struct aoc_method aoc_methods[] = {{0, 0}};aoc.h
1#ifndef AOC_H
2#define AOC_H
3
4#include <stdarg.h>
5#include <stddef.h>
6#include <stdint.h>
7#include <stdlib.h>
8#include <string.h>
9
10/* The only required boundary between infra and a solution.
11 * `input` is read-only and is not owned by the solution.
12 * The returned slice is allocated with malloc. It is the only
13 * block still live when the function returns. Infra copies it
14 * and then frees it.
15 */
16typedef struct {
17 uint8_t *p;
18 size_t l;
19} slice;
20
21/* p is null and l is 0. Infra uses this when a run has no output. */
22static const slice empty_slice = {0};
23
24typedef slice (*aoc_fn)(slice);
25
26/* One named method. The name is a C identifier, at most 31
27 * characters, and it is the URL suffix: /YYYY/D/P/<name>.
28 * estimate and span are examples, not a fixed list. A day
29 * exports as many as it wants. The array ends with {0, 0}.
30 * part1 and part2 are not entries in this list.
31 */
32struct aoc_method {
33 const char *name;
34 aoc_fn fn;
35};
36
37slice part1(slice input);
38slice part2(slice input);
39
40extern const struct aoc_method aoc_methods[];
41
42/* Provided by the runtime. Records msg and returns. */
43void aoc_fail(const char *msg);
44
45/* Stops the run when cond is false and reports msg. */
46_Noreturn void aoc_assert_fail(const char *msg);
47#ifndef aoc_assert
48#define aoc_assert(cond, msg) \
49 do { \
50 if (!(cond)) { \
51 aoc_assert_fail(msg); \
52 } \
53 } while (0)
54#endif
55
56/* Decimal text of a uint64_t is at most 20 digits. A sign and a
57 * little spare fit here. Size a number buffer from this.
58 */
59enum { AOC_I64_TEXT = 32 };
60
61/* Decimal digits of v. No sign. d has room for 20 digits. */
62static inline char *aoc_u64_text(char *d, uint64_t v) {
63 char tmp[AOC_I64_TEXT];
64 char *end = tmp + AOC_I64_TEXT;
65 char *p = end;
66 size_t n;
67 do {
68 *--p = (char)('0' + (v % 10ull));
69 v /= 10ull;
70 } while (v);
71 n = (size_t)(end - p);
72 memcpy(d, p, n);
73 return d + n;
74}
75
76/* Decimal digits of v. The minimum int64_t is not negated. */
77static inline char *aoc_i64_text(char *d, int64_t v) {
78 uint64_t u;
79 if (v < 0) {
80 *d++ = '-';
81 u = (uint64_t)(-(v + 1)) + 1ull;
82 } else {
83 u = (uint64_t)v;
84 }
85 return aoc_u64_text(d, u);
86}
87
88/* n values, one space between them. The author knows the order. */
89static inline char *aoc_u64s(char *d, const uint64_t *v, size_t n) {
90 size_t i;
91 for (i = 0; i < n; i++) {
92 if (i) {
93 *d++ = ' ';
94 }
95 d = aoc_u64_text(d, v[i]);
96 }
97 return d;
98}
99
100static inline char *aoc_i64s(char *d, const int64_t *v, size_t n) {
101 size_t i;
102 for (i = 0; i < n; i++) {
103 if (i) {
104 *d++ = ' ';
105 }
106 d = aoc_i64_text(d, v[i]);
107 }
108 return d;
109}
110
111static inline char *aoc_ints(char *d, const int *v, size_t n) {
112 size_t i;
113 for (i = 0; i < n; i++) {
114 if (i) {
115 *d++ = ' ';
116 }
117 d = aoc_i64_text(d, (int64_t)v[i]);
118 }
119 return d;
120}
121
122/* Write fmt at buf. Return the cursor for the next call.
123 * %d takes int. %i takes int64_t. %u takes uint64_t.
124 * %s takes a C string. %% is a percent sign.
125 * A literal run is memcpy.
126 * %D takes (int *, size_t). %I takes (int64_t *, size_t).
127 * %U takes (uint64_t *, size_t). One space between values.
128 */
129static inline char *aoc_vprintf(const char *fmt, char *buf, va_list ap) {
130 while (*fmt) {
131 const char *lit = fmt;
132 size_t n;
133 while (*fmt && *fmt != '%') {
134 fmt++;
135 }
136 n = (size_t)(fmt - lit);
137 if (n) {
138 memcpy(buf, lit, n);
139 buf += n;
140 }
141 if (*fmt != '%') {
142 break;
143 }
144 fmt++;
145 if (*fmt == '%') {
146 *buf++ = '%';
147 fmt++;
148 continue;
149 }
150 if (*fmt == 's') {
151 const char *s = va_arg(ap, const char *);
152 n = strlen(s);
153 if (n) {
154 memcpy(buf, s, n);
155 buf += n;
156 }
157 fmt++;
158 continue;
159 }
160 if (*fmt == 'd') {
161 buf = aoc_i64_text(buf, (int64_t)va_arg(ap, int));
162 fmt++;
163 continue;
164 }
165 if (*fmt == 'i') {
166 buf = aoc_i64_text(buf, va_arg(ap, int64_t));
167 fmt++;
168 continue;
169 }
170 if (*fmt == 'u') {
171 buf = aoc_u64_text(buf, va_arg(ap, uint64_t));
172 fmt++;
173 continue;
174 }
175 if (*fmt == 'D') {
176 const int *v = va_arg(ap, int *);
177 buf = aoc_ints(buf, v, va_arg(ap, size_t));
178 fmt++;
179 continue;
180 }
181 if (*fmt == 'I') {
182 const int64_t *v = va_arg(ap, int64_t *);
183 buf = aoc_i64s(buf, v, va_arg(ap, size_t));
184 fmt++;
185 continue;
186 }
187 if (*fmt == 'U') {
188 const uint64_t *v = va_arg(ap, uint64_t *);
189 buf = aoc_u64s(buf, v, va_arg(ap, size_t));
190 fmt++;
191 continue;
192 }
193 aoc_assert(0, "bad format");
194 }
195 return buf;
196}
197
198static inline char *aoc_printf(const char *fmt, char *buf, ...) {
199 va_list ap;
200 va_start(ap, buf);
201 buf = aoc_vprintf(fmt, buf, ap);
202 va_end(ap);
203 return buf;
204}
205
206/* Copy n bytes of text into a malloc'd slice. */
207static inline slice slice_from_text(const char *s, size_t n) {
208 uint8_t *p = malloc(n);
209 aoc_assert(p, "out of memory");
210 if (n) {
211 memcpy(p, s, n);
212 }
213 return (slice){p, n};
214}
215
216/* Decimal text of v, allocated at AOC_I64_TEXT. The minimum
217 * int64_t is not negated. slice.l is the bytes written.
218 */
219static inline slice slice_from_i64(int64_t v) {
220 char tmp[AOC_I64_TEXT];
221 char *d;
222 uint8_t *p;
223 size_t n;
224 d = aoc_printf("%i", tmp, v);
225 n = (size_t)(d - tmp);
226 p = malloc(AOC_I64_TEXT);
227 aoc_assert(p, "out of memory");
228 memcpy(p, tmp, n);
229 return (slice){p, n};
230}
231
232/* Parse one decimal slice into *out. A leading '-' is allowed.
233 * Returns 1 on success, 0 for invalid text or int64_t overflow.
234 */
235static inline int slice_to_i64(slice s, int64_t *out) {
236 size_t i = 0;
237 int neg = 0;
238 uint64_t u = 0;
239 if (!s.p || s.l == 0 || !out) {
240 return 0;
241 }
242 if (s.p[0] == '-') {
243 neg = 1;
244 i = 1;
245 if (s.l == 1) {
246 return 0;
247 }
248 }
249 for (; i < s.l; i++) {
250 uint8_t c = s.p[i];
251 if (c < '0' || c > '9') {
252 return 0;
253 }
254 uint64_t digit = (uint64_t)(c - '0');
255 uint64_t limit = (uint64_t)INT64_MAX + (uint64_t)neg;
256 if (u > (limit - digit) / 10u) {
257 return 0;
258 }
259 u = u * 10u + digit;
260 }
261 if (neg) {
262 *out = u == (uint64_t)INT64_MAX + 1u ? INT64_MIN : -(int64_t)u;
263 } else {
264 *out = (int64_t)u;
265 }
266 return 1;
267}
268
269#endifThe aha moment
The reindeer starts facing east, and turning costs a thousand times as much as stepping forward. That makes direction part of the problem, not a drawing annotation. Two routes reaching the same tile with different headings can have very different costs to continue. The local 141-by-141 maze has 10,100 open tiles, so four orientations per open tile give only 40,400 meaningful states. This is a manageable weighted graph.
Give each state three possible actions: rotate left in place for 1,000, rotate right in place for 1,000, or move forward into an open tile for one. Dijkstra's algorithm then minimizes the actual score. A plain BFS would minimize the number of actions rather than their unequal costs. Nor should we silently replace the score with “fewest turns, then fewest steps”: the rule is the numerical sum, and a sufficiently large difference in walking distance can outweigh a turn.
Rotations must remain independent actions. A common shortcut combines a turn with an immediate step into the new direction. That fails when the reindeer needs to turn around in a dead end or begins facing a wall: it may rotate twice without moving before it can leave. The second public example even starts with a turn. Modeling exactly the actions in the story avoids attaching an unintended movement requirement to rotation.
For part one, run Dijkstra from S facing east and take the smallest distance among all four orientations at E. Reaching E does not require a particular final heading. The local search examines 101,600 outgoing graph edges, a small amount of work. There is no need to enumerate routes or keep their full histories to find the optimal score.
Part two asks for tiles on any optimal route. Saving one predecessor per state would recover one good route, but it would lose equal-cost alternatives. Enumerating all optimal paths is possible on some inputs—the local maze has sixteen optimal action sequences—but the number of alternatives can grow through repeated splits and merges. We only need their union of tiles, not a list of every way to traverse that union.
Ask a state two independent questions: what is the cheapest score to get here from the start, and what is the cheapest score to reach the end from here? The first Dijkstra already answered the first question. For the second, run Dijkstra backward from all four end orientations. Reverse each graph edge: rotations remain rotations, while a reversed forward move goes one cell backward without changing the stored heading. Starting an ordinary forward walk from E would not compute the same distances.
Let F(state) be the forward distance, B(state) the backward distance and C the optimal complete score. A state lies on some optimal route exactly when F + B = C. If equality holds, its cheapest prefix and suffix concatenate into an optimal route. If it lies on an optimal route, neither portion can be more expensive than a cheaper substitute, so equality must hold. Aha, two distance tables describe the entire family of optimal routes without storing that family.
Check the equality for each orientation of each tile, and count the tile once if any orientation qualifies. The local result has 693 qualifying orientation states spread over 568 tiles. Using min(F) and min(B) separately at a tile could combine incompatible headings, so the addition must happen for the same complete state before collapsing orientations to a tile.
The implementation accepts mazes up to 160 by 160 and uses indexed heaps bounded by the four-state-per-cell inventory. It explicitly refuses an unreachable end. The lesson extends beyond this maze: after finding an optimum, asking which choices can participate in any optimum often becomes a meeting of forward and backward costs. The crucial prerequisite is still the right state—in this case, position plus heading.
See also
Categories for 2015–2024 adapted from u/Boojum’s 500 Stars: A Categorization and Mega-Guide ↗. A day can belong to several categories. Tags from 2025 onward are our additions.
Try your input
One POST, one reply. Your input is not saved.