2023 AoC Day 17 – Clumsy Crucible

This is a solution to Advent of Code 2023 day 17, written in Raku.

https://adventofcode.com/2023/day/17

Part One

Directing the crucible from the lava pool to the machine parts factory, but not moving more than three consecutive blocks in the same direction, what is the least heat loss it can incur?

constant \size = 13;
my @weights[size;size] = '17-test.txt'.IO.lines>>.comb>>.map(*.Int);
my @distance[size;size];
my @prev[size;size];
my @visited[size;size];

@distance[0;0] = 0;

sub neighbours($u) {
    my @neighbours = -1+0i, 0-1i, 0+1i, 1+0i;
    @neighbours.map(* + $u).grep(-> $n { 0 <= $n.re < size && 0 <= $n.im < size && !@visited[$n.re;$n.im]})
}

my $start = 0+0i;
@distance[0;0] = 0;
@visited[0;0] = True;

my @q = $start; neighbours($start);
while @q {
    my $u = @q.shift;
    @visited[$u.re.Int;$u.im.Int] = True;
    for neighbours($u) -> $v {
        my $alt = @distance[$u.re;$u.im] + @weights[$v.re;$v.im];
        my $dist = @distance[$v.re;$v.im] // Inf;
        if $alt < $dist {
            @distance[$v.re.Int; $v.im.Int] = $alt;
        }
        @q.push($v);
    }
    say @q;
}

Part Two

raku