2019 / Day 18

Many-Worlds Interpretation

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* The local vault is 81 by 81, with 26 keys, 26 doors, 3201 open cells, and
4 * only four cycles around the central junction. SIDE = 96 and KEYS = 26 bound
5 * the grid. Precompute shortest paths and their door/intermediate-key
6 * requirements; confirm every alternate route has a superset of the first route
7 * requirements, otherwise refuse that maze. This grounds the single-path graph
8 * shortcut. Memoize only (collected keys, robot positions), not the whole grid;
9 * four robots use the same graph after the stated entrance surgery. The local
10 * searches visit 23210 and 49966 memo states; STATES = 131072 bounds that
11 * search. */
12
13typedef struct {
14    slice s;
15    size_t i;
16} Parser;
17
18static int space(uint8_t c) {
19    return c == ' ' || c == '\t' || c == '\r' || c == '\n';
20}
21
22static void ws(Parser *p) {
23    while (p->i < p->s.l && space(p->s.p[p->i])) {
24        p->i++;
25    }
26}
27
28static void text(Parser *p, const char *s) {
29    size_t n = strlen(s);
30    aoc_assert(n <= p->s.l - p->i && !memcmp(p->s.p + p->i, s, n), "bad input");
31    p->i += n;
32}
33
34static int64_t number(Parser *p, int64_t cap) {
35    int neg = 0;
36    if (p->i < p->s.l && p->s.p[p->i] == '-') {
37        neg = 1;
38        p->i++;
39    }
40    size_t b = p->i;
41    int64_t v = 0;
42    while (p->i < p->s.l && p->s.p[p->i] >= '0' && p->s.p[p->i] <= '9') {
43        int d = p->s.p[p->i++] - '0';
44        aoc_assert(d <= cap && v <= (cap - d) / 10, "integer exceeds cap");
45        v = v * 10 + d;
46    }
47    aoc_assert(p->i > b, "expected integer");
48    return neg ? -v : v;
49}
50
51static void finish(Parser *p) {
52    ws(p);
53    aoc_assert(p->i == p->s.l, "trailing input");
54}
55
56static slice line(Parser *p) {
57    size_t b = p->i;
58    while (p->i < p->s.l && p->s.p[p->i] != '\n') {
59        p->i++;
60    }
61    size_t e = p->i;
62    if (e > b && p->s.p[e - 1] == '\r') {
63        e--;
64    }
65    if (p->i < p->s.l) {
66        p->i++;
67    }
68    return (slice){p->s.p + b, e - b};
69}
70
71enum {
72    SIDE = 96,
73    CELLS = SIDE * SIDE,
74    KEYS = 26,
75    ROBOTS = 4,
76    NODES = KEYS + ROBOTS,
77    STATES = 131072,
78    TABLE = 2 * STATES,
79    INF = 100000000
80};
81
82static uint8_t grid[CELLS];
83static int width, height, robots, source[NODES];
84static uint32_t all;
85
86typedef struct {
87    int distance;
88    uint32_t doors, through;
89} Edge;
90
91static Edge edges[NODES][KEYS];
92static int distance[CELLS], queue[CELLS];
93static uint32_t doors[CELLS], through[CELLS];
94
95typedef struct {
96    uint64_t key;
97    int value;
98} Memo;
99
100static Memo memo[TABLE];
101static int states;
102
103static void load(slice in, int second) {
104    memset(grid, '#', sizeof grid);
105    for (int i = 0; i < NODES; i++) {
106        source[i] = -1;
107    }
108    Parser p = {in, 0};
109    width = -1;
110    height = robots = 0;
111    all = 0;
112    while (p.i < in.l) {
113        slice row = line(&p);
114        aoc_assert(row.l && row.l <= SIDE && height < SIDE, "vault grid cap");
115        if (width < 0) {
116            width = (int)row.l;
117        }
118        aoc_assert(row.l == (size_t)width, "ragged vault grid");
119        for (size_t x = 0; x < row.l; x++) {
120            int at = height * SIDE + (int)x;
121            uint8_t c = row.p[x];
122            aoc_assert(c == '#' || c == '.' || c == '@' ||
123                           (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'),
124                       "bad vault tile");
125            grid[at] = c;
126            if (c == '@') {
127                aoc_assert(robots < ROBOTS, "too many robots");
128                source[KEYS + robots++] = at;
129            }
130            if (c >= 'a' && c <= 'z') {
131                int k = c - 'a';
132                aoc_assert(source[k] < 0, "duplicate key");
133                source[k] = at;
134                all |= 1u << k;
135            }
136        }
137        height++;
138    }
139    aoc_assert(all, "empty key set");
140    if (second && robots == 1) {
141        int at = source[KEYS], x = at % SIDE, y = at / SIDE;
142        aoc_assert(x > 0 && x + 1 < width && y > 0 && y + 1 < height,
143                   "entrance at boundary");
144        for (int dy = -1; dy <= 1; dy++) {
145            for (int dx = -1; dx <= 1; dx++) {
146                if (dx || dy) {
147                    aoc_assert(grid[at + dy * SIDE + dx] == '.',
148                               "unsupported entrance surgery");
149                }
150            }
151        }
152        grid[at] = grid[at - 1] = grid[at + 1] = grid[at - SIDE] =
153            grid[at + SIDE] = '#';
154        robots = 0;
155        for (int dy = -1; dy <= 1; dy += 2) {
156            for (int dx = -1; dx <= 1; dx += 2) {
157                int pos = at + dy * SIDE + dx;
158                grid[pos] = '@';
159                source[KEYS + robots++] = pos;
160            }
161        }
162    }
163    aoc_assert(robots == (second ? ROBOTS : 1), "wrong robot count");
164}
165
166static void graph(void) {
167    memset(edges, 0, sizeof edges);
168    static const int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
169    for (int s = 0; s < NODES; s++) {
170        if (source[s] < 0) {
171            continue;
172        }
173        for (int i = 0; i < CELLS; i++) {
174            distance[i] = -1;
175        }
176        int head = 0, tail = 0, start = source[s];
177        queue[tail++] = start;
178        distance[start] = 0;
179        doors[start] = through[start] = 0;
180        while (head < tail) {
181            int at = queue[head++];
182            for (int d = 0; d < 4; d++) {
183                int x = at % SIDE + dx[d], y = at / SIDE + dy[d];
184                if (x < 0 || x >= width || y < 0 || y >= height) {
185                    continue;
186                }
187                int next = y * SIDE + x;
188                uint8_t c = grid[next];
189                if (c == '#') {
190                    continue;
191                }
192                uint32_t req = doors[at], keys = through[at];
193                if (c >= 'A' && c <= 'Z') {
194                    req |= 1u << (c - 'A');
195                }
196                if (c >= 'a' && c <= 'z') {
197                    keys |= 1u << (c - 'a');
198                }
199                if (distance[next] >= 0) {
200                    aoc_assert(!(doors[next] & ~req) &&
201                                   !(through[next] & ~keys),
202                               "vault has alternate key/door route");
203                    continue;
204                }
205                distance[next] = distance[at] + 1;
206                doors[next] = req;
207                through[next] = keys;
208                aoc_assert(tail < CELLS, "vault BFS cap");
209                queue[tail++] = next;
210            }
211        }
212        for (int k = 0; k < KEYS; k++) {
213            int at = source[k];
214            if (at >= 0 && distance[at] > 0) {
215                edges[s][k] =
216                    (Edge){distance[at], doors[at], through[at] & ~(1u << k)};
217            }
218        }
219    }
220}
221
222static int search(uint32_t keys, int *positions) {
223    if (keys == all) {
224        return 0;
225    }
226    uint64_t key = keys;
227    for (int i = 0; i < robots; i++) {
228        key = (key << 5) | (uint64_t)positions[i];
229    }
230    key++;
231    uint64_t mixed = key * UINT64_C(11400714819323198485);
232    size_t slot = (size_t)(mixed ^ (mixed >> 32)) & (TABLE - 1);
233    while (memo[slot].key && memo[slot].key != key) {
234        slot = (slot + 1) & (TABLE - 1);
235    }
236    if (memo[slot].key) {
237        return memo[slot].value;
238    }
239    aoc_assert(states++ < STATES, "vault state cap");
240    int best = INF;
241    for (int r = 0; r < robots; r++) {
242        int old = positions[r];
243        for (int k = 0; k < KEYS; k++) {
244            Edge e = edges[old][k];
245            if ((keys & (1u << k)) || !e.distance || (e.doors & ~keys) ||
246                (e.through & ~keys)) {
247                continue;
248            }
249            positions[r] = k;
250            int value = search(keys | (1u << k), positions);
251            positions[r] = old;
252            if (value < INF && value + e.distance < best) {
253                best = value + e.distance;
254            }
255        }
256    }
257    /* Descendants may hash into this slot while it was being computed. */
258    slot = (size_t)(mixed ^ (mixed >> 32)) & (TABLE - 1);
259    while (memo[slot].key && memo[slot].key != key) {
260        slot = (slot + 1) & (TABLE - 1);
261    }
262    memo[slot] = (Memo){key, best};
263    return best;
264}
265
266static slice solve(slice in, int second) {
267    load(in, second);
268    graph();
269    memset(memo, 0, sizeof memo);
270    states = 0;
271    int positions[ROBOTS];
272    for (int i = 0; i < robots; i++) {
273        positions[i] = KEYS + i;
274    }
275    int answer = search(0, positions);
276    aoc_assert(answer < INF, "keys are unreachable");
277    return slice_from_i64(answer);
278}
279
280slice part1(slice in) {
281    return solve(in, 0);
282}
283
284slice part2(slice in) {
285    return solve(in, 1);
286}
287
288const 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#endif

The aha moment

The vault invites a familiar plan: find the nearest key, collect it, and repeat. The story blocks that shortcut before we even reach part two. In its larger example, key e is closer, but visiting d first gives a shorter complete journey. A key's value includes the doors it opens and where it leaves us for the next trip. Local distance alone cannot decide the best order.

The local map is 81 by 81, with 3,201 traversable cells, 26 keys, and 26 doors. Trying every key order suggests 26 factorial possibilities, an absurdly large number even though many orders are impossible. Searching the grid also needs more state than just position: standing at the same square with key a is different from standing there without it, because door A is now passable.

A correct cell-level search state is position plus the set of collected keys. But the naive product of 3,201 cells and 2 to the power 26 key sets is about 215 billion possibilities. That is an upper bound, not a prediction of the actual search, yet it tells us to look for structure before allocating a table.

Most corridor steps do not change our choices. The interesting events are reaching keys. Precompute distances between the entrance and keys, and between pairs of keys, then let the main search jump from one such event to the next. Record which doors and intermediate keys each route crosses. A twenty-step corridor becomes one edge with cost twenty, rather than twenty separate search states.

There is a trap in this compression too. The shortest geometric path to a key might pass through a locked door, while a longer path avoids it. Keeping only that shortest path would incorrectly declare the key unreachable. A general solver must retain useful alternatives, such as a longer route with fewer requirements.

This implementation takes a narrower shortcut and verifies it. The local maze is almost a tree: it has 3,204 neighbor edges among 3,201 cells, giving only four independent cycles. During each breadth-first precomputation, it checks that the first path to a tile requires no door or intermediate key absent from any alternate route examined. Thus the stored shortest path is never more restrictive than an alternative. A maze violating this condition is explicitly refused rather than silently using an invalid compressed graph.

Intermediate keys also matter because walking across one collects it. The search treats each move as collecting its next new key, so it permits a compressed edge only if every intermediate key is already owned. If an uncollected key lies along the way, choose that key as the next event first. This preserves the automatic collection rule without allowing a route to slip past a key unnoticed.

Now the recursive decision is small and concrete. For each reachable uncollected key, pay the route distance, mark the key collected, move to its node, and ask for the cheapest way to finish. Cache that remaining cost by current node and key set. Different earlier orders that lead to the same state have exactly the same remaining possibilities, so their common suffix need only be solved once. Each transition adds a key, which also bounds recursion depth.

Part two replaces the central entrance with four starts and walls. Four vaults look independent, but their locks are not: a key collected by one robot instantly opens the matching door for another. Solving each quarter separately and adding the answers loses these dependencies. Keep one shared key set and four current positions. A transition chooses which robot collects the next reachable key, leaving the other positions unchanged. The objective adds movement steps; it is not the maximum of four simultaneous travel times.

Despite the frightening initial bounds, the local searches visit 23,210 memo states for one robot and 49,966 for four. Door requirements and the corridor structure eliminate most theoretical combinations. These measured state counts justify the implementation's 131,072-state cap, alongside a 96-by-96 map, at most 26 distinct keys, and one or four robots. It checks the entrance modification, route-requirement condition, and reachability explicitly. The breakthrough is identifying which history still matters: keys and positions summarize the future, while the order used to reach that state can be forgotten.

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.