Task 18

Thorn Thaler - <

2025-12-01

1 Setup

1.1 Libraries

library(httr)
library(xml2)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)

1.2 Retrieve Data from AoC

session_cookie <- set_cookies(session = keyring::key_get("AoC-GitHub-Cookie"))
base_url <- paste0("https://adventofcode.com/", params$year, "/day/", params$task_nr)
puzzle <- GET(base_url,
              session_cookie) %>% 
  content(encoding = "UTF-8") %>% 
  xml_find_all("///article") %>% 
  lapply(as.character)

parse_puzzle_data <- function(text_block = readClipboard()) {
  if (length(text_block) == 1L) {
    text_block <- text_block %>% 
      str_split("\n") %>% 
      extract2(1L) %>% 
      keep(nzchar)
  }
  text_block %>% 
    str_split("") %>% 
    do.call(rbind, .) 
}

puzzle_data <- local({
  GET(paste0(base_url, "/input"),
      session_cookie) %>% 
    content(encoding = "UTF-8") %>% 
    parse_puzzle_data()
})

2 Puzzle Day 18

2.1 Part 1

2.1.1 Description

— Day 18: Many-Worlds Interpretation —

As you approach Neptune, a planetary security system detects you and activates a giant tractor beam on Triton! You have no choice but to land.

A scan of the local area reveals only one interesting feature: a massive underground vault. You generate a map of the tunnels (your puzzle input). The tunnels are too narrow to move diagonally.

Only one entrance (marked @) is present among the open passages (marked .) and stone walls (#), but you also detect an assortment of keys (shown as lowercase letters) and doors (shown as uppercase letters). Keys of a given letter open the door of the same letter: a opens A, b opens B, and so on. You aren’t sure which key you need to disable the tractor beam, so you’ll need to collect all of them.

For example, suppose you have the following map:

#########
#b.A.@.a#
#########

Starting from the entrance (@), you can only access a large door (A) and a key (a). Moving toward the door doesn’t help you, but you can move 2 steps to collect the key, unlocking A in the process:

#########
#b.....@#
#########

Then, you can move 6 steps to collect the only other key, b:

#########
#@......#
#########

So, collecting every key took a total of 8 steps.

Here is a larger example:

########################
#f.D.E.e.C.b.A.@.a.B.c.#
######################.#
#d.....................#
########################

The only reasonable move is to take key a and unlock door A:

########################
#f.D.E.e.C.b.....@.B.c.#
######################.#
#d.....................#
########################

Then, do the same with key b:

########################
#f.D.E.e.C.@.........c.#
######################.#
#d.....................#
########################

…and the same with key c:

########################
#f.D.E.e.............@.#
######################.#
#d.....................#
########################

Now, you have a choice between keys d and e. While key e is closer, collecting it now would be slower in the long run than collecting key d first, so that’s the best choice:

########################
#f...E.e...............#
######################.#
#@.....................#
########################

Finally, collect key e to unlock door E, then collect key f, taking a grand total of 86 steps.

Here are a few more examples:

  • ########################
    #...............b.C.D.f#
    #.######################
    #.....@.a.B.c.d.A.e.F.g#
    ########################
    

    Shortest path is 132 steps: b, a, c, d, f, e, g

  • #################
    #i.G..c...e..H.p#
    ########.########
    #j.A..b...f..D.o#
    ########@########
    #k.E..a...g..B.n#
    ########.########
    #l.F..d...h..C.m#
    #################
    

    Shortest paths are 136 steps;
    one is: a, f, b, j, g, n, h, d, l, o, e, p, c, i, k, m

  • ########################
    #@..............ac.GI.b#
    ###d#e#f################
    ###A#B#C################
    ###g#h#i################
    ########################
    

    Shortest paths are 81 steps; one is: a, c, f, i, d, g, b, e, h

How many steps is the shortest path that collects all of the keys?

2.1.2 Solution

For this puzzle we fall back to C++ for speed. The most important performance trick though is to first reduce the maze to a graph, where each node represents either a key a-z or the entrance @. The edges represent the shortest paths between those points and we also store the key requirements for each path.

This reduces the problem to finding the shortest path between the keys / entrance, where we also keep track about the collected keys. Then we use a Dijkstra algorithm to find the shortest path which connects all keys, while making sure that we do not enter a field, if we did not find the corresponding key yet.

#ifndef STANDALONE
#include <Rcpp.h>
#define COUT Rcpp::Rcout
using namespace Rcpp;
#else
#define COUT std::cout
#include <iostream>
#endif
#include <array>
#include <queue>
#include <tuple>
#include <unordered_map>
#include <vector>

struct Coord {
    int x;
    int y;
    char label;
    bool operator==(const Coord& other) const { return x == other.x && y == other.y; }
    Coord operator+(const Coord& other) const { return {x + other.x, y + other.y, 0}; }
    bool is_valid(int nrow, int ncol) const { return x >= 0 && x < ncol && y >= 0 && y < nrow; }
};

struct CoordHash {
    std::size_t operator()(const Coord& c) const {
      std::size_t h1 = std::hash<int> {}(c.x);
      std::size_t h2 = std::hash<int> {}(c.y);
      return h1 ^ (h2 << 1);
    }
};

struct State {
    Coord coord;
    int key_bitmask;
    bool operator==(const State& other) const {
      return coord == other.coord && key_bitmask == other.key_bitmask;
    }
};

struct StateHash {
    std::size_t operator()(const State& s) const {
      std::size_t h1 = CoordHash {}(s.coord);
      std::size_t h2 = std::hash<int> {}(s.key_bitmask);
      std::size_t hash = h1;
      hash ^= h2 + 0x9e3779b9 + (hash << 6) + (hash >> 2);
      return hash;
    }
};

struct MultiState {
    std::array<Coord, 4> coords;
    int key_bitmask;
    bool operator==(const MultiState& other) const {
      return coords == other.coords && key_bitmask == other.key_bitmask;
    }
    Coord& operator[](std::size_t i) { return coords[i]; }
    const Coord& operator[](std::size_t i) const { return coords[i]; }
};

struct MultiStateHash {
    std::size_t operator()(const MultiState& ms) const {
      std::size_t seed = 0;
      for (const auto& c : ms.coords) {
        std::size_t h = CoordHash {}(c);
        seed ^= h + 0x9e3779b9 + (seed << 6) + (seed >> 2);
      }
      std::size_t h2 = std::hash<int> {}(ms.key_bitmask);
      seed ^= h2 + 0x9e3779b9 + (seed << 6) + (seed >> 2);
      return seed;
    }
};

struct Field {
    State state;
    int distance;
    bool operator==(const Field& other) const {
      return state == other.state && distance == other.distance;
    }
};

using Path = std::unordered_map<char, std::vector<Field>>;

Path bfs(const std::vector<std::string>& maze, const std::vector<Coord>& pois) {
  Path result;
  int nrow = maze.size();
  int ncol = maze[0].size();
  const std::array<Coord, 4> directions = {{{0, 1, '>'}, {1, 0, 'v'}, {0, -1, '<'}, {-1, 0, '^'}}};
  for (const auto& start : pois) {
    std::queue<Field> pq;
    std::vector<std::vector<bool>> visited(nrow, std::vector<bool>(ncol, false));
    pq.push({{start, 0}, 0});
    visited[start.y][start.x] = true;
    while (!pq.empty()) {
      auto field = pq.front();
      pq.pop();

      for (const auto& dir : directions) {
        Coord nb = field.state.coord + dir;
        if (!nb.is_valid(nrow, ncol) || maze[nb.y][nb.x] == '#' || visited[nb.y][nb.x]) {
          continue;
        }
        char cell = maze[nb.y][nb.x];
        int new_key_bitmask = field.state.key_bitmask;
        if (cell >= 'A' && cell <= 'Z') {
          new_key_bitmask |= (1 << (cell - 'A'));
        } else if (cell >= 'a' && cell <= 'z') {
          nb.label = cell;
          Field new_field = {{nb, new_key_bitmask}, field.distance + 1};
          result[start.label].push_back(new_field);
        }
        visited[nb.y][nb.x] = true;
        pq.push({{nb, new_key_bitmask}, field.distance + 1});
      }
    }
  }
  return result;
}

int get_key_path_length(const Path& path, const Coord& start, int nr_keys) {
  std::unordered_map<State, int, StateHash> dp;
  auto cmp = [](const std::pair<int, State>& a, const std::pair<int, State>& b) {
    return a.first > b.first;
  };
  std::priority_queue<std::pair<int, State>, std::vector<std::pair<int, State>>, decltype(cmp)> pq(
      cmp);
  State state = {start, 0};
  int all_keys_found = (1 << nr_keys) - 1;
  pq.push({0, state});
  while (!pq.empty()) {
    auto [distance, cur_state] = pq.top();
    pq.pop();

    if (dp.count(cur_state) && distance >= dp[cur_state]) {
      continue;
    }

    dp[cur_state] = distance;

    if (cur_state.key_bitmask == all_keys_found) {
      return distance;
    }

    for (const auto& nb : path.at(cur_state.coord.label)) {
      if ((cur_state.key_bitmask & nb.state.key_bitmask) != nb.state.key_bitmask) {
        continue;
      }

      int new_key = cur_state.key_bitmask;
      new_key |= (1 << (nb.state.coord.label - 'a'));

      State new_state = {nb.state.coord, new_key};
      int new_distance = distance + nb.distance;

      if (!dp.count(new_state) || new_distance < dp[new_state]) {
        pq.push({new_distance, new_state});
      }
    }
  }
  return -1;
}

int get_key_path_length(const Path& path, const std::array<Coord, 4>& starts, int nr_keys) {
  std::unordered_map<MultiState, int, MultiStateHash> dp;
  auto cmp = [](const std::pair<int, MultiState>& a, const std::pair<int, MultiState>& b) {
    return a.first > b.first;
  };
  std::priority_queue<std::pair<int, MultiState>,
                      std::vector<std::pair<int, MultiState>>,
                      decltype(cmp)>
      pq(cmp);
  int all_keys_found = (1 << nr_keys) - 1;
  MultiState start_state = {starts, 0};
  pq.push({0, start_state});
  while (!pq.empty()) {
    auto [distance, cur_states] = pq.top();
    pq.pop();

    if (dp.count(cur_states) && distance > dp[cur_states]) {
      continue;
    }

    if (cur_states.key_bitmask == all_keys_found) {
      return distance;
    }
    int keys = cur_states.key_bitmask;

    for (std::size_t i = 0; i < cur_states.coords.size(); ++i) {
      Coord pos = cur_states[i];
      for (const auto& nb : path.at(pos.label)) {
        if ((keys & nb.state.key_bitmask) != nb.state.key_bitmask) {
          continue;
        }

        int new_keys = keys | (1 << (nb.state.coord.label - 'a'));
        MultiState new_states = cur_states;
        new_states.key_bitmask = new_keys;
        new_states[i] = nb.state.coord;

        int new_distance = distance + nb.distance;

        if (!dp.count(new_states) || new_distance < dp[new_states]) {
          dp[new_states] = new_distance;
          pq.push({new_distance, new_states});
        }
      }
    }
  }
  return -1;
}

#ifndef STANDALONE
// [[Rcpp::export]]
int get_key_path_length(const CharacterMatrix& maze) {
  std::vector<std::string> maze_vec;
  std::vector<Coord> pois;
  Coord start;
  int nrow = maze.nrow();
  int ncol = maze.ncol();
  for (int i = 0; i < nrow; ++i) {
    std::string row_str;
    for (int j = 0; j < ncol; ++j) {
      char cell = as<char>(maze(i, j));
      row_str += cell;
      if (cell == '@' || (cell >= 'a' && cell <= 'z')) {
        Coord poi = {j, i, cell};
        pois.push_back(poi);
        if (cell == '@') {
          start = poi;
        }
      }
    }
    maze_vec.push_back(row_str);
  }
  Path result = bfs(maze_vec, pois);
  return get_key_path_length(result, start, pois.size() - 1);
}

// [[Rcpp::export]]
int get_key_path_length_multi(const CharacterMatrix& maze) {
  std::vector<std::string> maze_vec;
  std::vector<Coord> pois;
  Coord orig_start = {0, 0};
  int nrow = maze.nrow();
  int ncol = maze.ncol();
  for (int i = 0; i < nrow; ++i) {
    std::string row_str;
    for (int j = 0; j < ncol; ++j) {
      char cell = as<char>(maze(i, j));
      row_str += cell;
      if (cell == '@' || (cell >= 'a' && cell <= 'z')) {
        Coord poi = {j, i, cell};
        if (cell == '@') {
          orig_start = poi;
        } else {
          pois.push_back(poi);
        }
      }
    }
    maze_vec.push_back(row_str);
  }
  int idx = 0;
  std::array<Coord, 4> starts;
  for (int j = -1; j < 2; ++j) {
    for (int i = -1; i < 2; ++i) {
      if (j == 0 || i == 0) {
        maze_vec[orig_start.y + j][orig_start.x + i] = '#';
      } else {
        char entrance = '1' + idx;
        maze_vec[orig_start.y + j][orig_start.x + i] = entrance;
        starts[idx] = {orig_start.x + i, orig_start.y + j, entrance};
        pois.push_back(starts[idx++]);
      }
    }
  }
  Path result = bfs(maze_vec, pois);
  return get_key_path_length(result, starts, pois.size() - 4);
}

#else
int main() {
  std::vector<std::string> maze_vec = {"#################",
                                       "#i.G..c...e..H.p#",
                                       "########.########",
                                       "#j.A..b...f..D.o#",
                                       "########@########",
                                       "#k.E..a...g..B.n#",
                                       "########.########",
                                       "#l.F..d...h..C.m#",
                                       "#################"};
  std::vector<Coord> pois;
  Coord start;
  int nrow = maze_vec.size();
  int ncol = maze_vec[0].size();
  for (int i = 0; i < nrow; ++i) {
    for (int j = 0; j < ncol; ++j) {
      char cell = maze_vec[i][j];
      if (cell == '@' || (cell >= 'a' && cell <= 'z')) {
        Coord poi = {j, i, cell};
        pois.push_back(poi);
        if (cell == '@') {
          start = poi;
        }
      }
    }
  }
  Path result = bfs(maze_vec, pois);
  COUT << get_key_path_length(result, start, pois.size() - 1) << std::endl;

  return 0;
}
#endif
get_key_path_length(puzzle_data)
## [1] 4248

2.2 Part 2

2.2.1 Description

— Part Two —

You arrive at the vault only to discover that there is not one vault, but four - each with its own entrance.

On your map, find the area in the middle that looks like this:

...
.@.
...

Update your map to instead use the correct data:

@#@
###
@#@

This change will split your map into four separate sections, each with its own entrance:

#######       #######
#a.#Cd#       #a.#Cd#
##...##       ##@#@##
##.@.##  -->  #######
##...##       ##@#@##
#cB#Ab#       #cB#Ab#
#######       #######

Because some of the keys are for doors in other vaults, it would take much too long to collect all of the keys by yourself. Instead, you deploy four remote-controlled robots. Each starts at one of the entrances (@).

Your goal is still to collect all of the keys in the fewest steps, but now, each robot has its own position and can move independently. You can only remotely control a single robot at a time. Collecting a key instantly unlocks any corresponding doors, regardless of the vault in which the key or door is found.

For example, in the map above, the top-left robot first collects key a, unlocking door A in the bottom-right vault:

#######
#@.#Cd#
##.#@##
#######
##@#@##
#cB#.b#
#######

Then, the bottom-right robot collects key b, unlocking door B in the bottom-left vault:

#######
#@.#Cd#
##.#@##
#######
##@#.##
#c.#.@#
#######

Then, the bottom-left robot collects key c:

#######
#@.#.d#
##.#@##
#######
##.#.##
#@.#.@#
#######

Finally, the top-right robot collects key d:

#######
#@.#.@#
##.#.##
#######
##.#.##
#@.#.@#
#######

In this example, it only took 8 steps to collect all of the keys.

Sometimes, multiple robots might have keys available, or a robot might have to wait for multiple keys to be collected:

###############
#d.ABC.#.....a#
######@#@######
###############
######@#@######
#b.....#.....c#
###############

First, the top-right, bottom-left, and bottom-right robots take turns collecting keys a, b, and c, a total of 6 + 6 + 6 = 18 steps. Then, the top-left robot can access key d, spending another 6 steps; collecting all of the keys here takes a minimum of 24 steps.

Here’s a more complex example:

#############
#DcBa.#.GhKl#
#.###@#@#I###
#e#d#####j#k#
###C#@#@###J#
#fEbA.#.FgHi#
#############
  • Top-left robot collects key a.
  • Bottom-left robot collects key b.
  • Top-left robot collects key c.
  • Bottom-left robot collects key d.
  • Top-left robot collects key e.
  • Bottom-left robot collects key f.
  • Bottom-right robot collects key g.
  • Top-right robot collects key h.
  • Bottom-right robot collects key i.
  • Top-right robot collects key j.
  • Bottom-right robot collects key k.
  • Top-right robot collects key l.

In the above example, the fewest steps to collect all of the keys is 32.

Here’s an example with more choices:

#############
#g#f.D#..h#l#
#F###e#E###.#
#dCba@#@BcIJ#
#############
#nK.L@#@G...#
#M###N#H###.#
#o#m..#i#jk.#
#############

One solution with the fewest steps is:

  • Top-left robot collects key e.
  • Top-right robot collects key h.
  • Bottom-right robot collects key i.
  • Top-left robot collects key a.
  • Top-left robot collects key b.
  • Top-right robot collects key c.
  • Top-left robot collects key d.
  • Top-left robot collects key f.
  • Top-left robot collects key g.
  • Bottom-right robot collects key k.
  • Bottom-right robot collects key j.
  • Top-right robot collects key l.
  • Bottom-left robot collects key n.
  • Bottom-left robot collects key m.
  • Bottom-left robot collects key o.

This example requires at least 72 steps to collect all keys.

After updating your map and using the remote-controlled robots, what is the fewest steps necessary to collect all of the keys?

2.2.2 Solution

For the second part, we rebuild the maze and follow the same idea. But this time we let all 4 robots walk at the same time and amend our priority queue to keep track about all 4 positions.

get_key_path_length_multi(puzzle_data)
## [1] 1878