--- Day 9: All in a Single Night ---

Every year, Santa manages to deliver all of his presents in a single night.

This year, however, he has some new locations to visit; his elves have provided him the distances between every pair of locations. He can start and end at any two (different) locations he wants, but he must visit each location exactly once. What is the shortest distance he can travel to achieve this?

For example, given the following distances:

London to Dublin = 464
London to Belfast = 518
Dublin to Belfast = 141

The possible routes are therefore:

Dublin -> London -> Belfast = 982
London -> Dublin -> Belfast = 605
London -> Belfast -> Dublin = 659
Dublin -> Belfast -> London = 659
Belfast -> Dublin -> London = 605
Belfast -> London -> Dublin = 982

The shortest of these is London -> Dublin -> Belfast = 605, and so the answer is 605 in this example.

What is the distance of the shortest route?

--- Part Two ---

The next year, just to show off, Santa decides to take the route with the longest distance instead.

He can still start and end at any two (different) locations he wants, and he still must visit each location exactly once.

For example, given the distances above, the longest route would be 982 via (for example) Dublin -> London -> Belfast.

What is the distance of the longest route?

Rust Solution

use rustgym_util::*;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt::Write;
use std::io::*;

pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {
    let it = reader.lines().map(|l| l.unwrap());
    let mut id: HashMap<String, usize> = HashMap::new();
    let mut adj: HashMap<usize, Vec<(usize, i32)>> = HashMap::new();
    for line in it {
        let words: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect();
        let size = id.len();
        let u = *id.entry(words[0].clone()).or_insert(size);
        let size = id.len();
        let v = *id.entry(words[2].clone()).or_insert(size);
        let val = words[4].parse::<i32>().unwrap();
        adj.entry(u).or_default().push((v, val));
        adj.entry(v).or_default().push((u, val));
    let n = id.len();
    let mut res1 = std::i32::MAX;
    let mut res2 = 0;
    for i in 0..n {
        let mut visited = HashSet::new();
        dfs(i, 0, &mut visited, &mut res1, &mut res2, &adj, n);
    writeln!(writer, "{}", res1).unwrap();
    writeln!(writer, "{}", res2).unwrap();

fn dfs(
    u: usize,
    dist: i32,
    visited: &mut HashSet<usize>,
    min: &mut i32,
    max: &mut i32,
    adj: &HashMap<usize, Vec<(usize, i32)>>,
    n: usize,
) {
    if visited.len() == n {
        *min = (*min).min(dist);
        *max = (*max).max(dist);
    for &(v, d) in &adj[&u] {
        if visited.insert(v) {
            dfs(v, dist + d, visited, min, max, adj, n);

advent_of_code!(test, "input.txt", "output.txt");

Having problems with this solution? Click here to submit an issue on github.