#lang curly-fn racket (require "scripts/aoc.rkt") ;; solution for day 12 (define (grid-h grid) (vector-length grid)) (define (grid-w grid) (vector-length (vector-ref grid 0))) (define (grid-ref grid y x) (vector-ref (vector-ref grid y) x)) (define (grid-find grid c) (for*/first ([y (in-range (grid-h grid))] [x (in-range (grid-w grid))] #:when (eq? c (grid-ref grid y x))) (cons x y))) (define (part1 input) (match-define (list grid G) input) (define-values [a b] (dijkstra G (grid-find grid #\E))) (hash-ref a (grid-find grid #\S))) (define (part2 input) (match-define (list grid G) input) (define-values [a b] (dijkstra G (grid-find grid #\E))) (apply min (for*/list ([y (in-range (grid-h grid))] [x (in-range (grid-w grid))] #:when (eq? (grid-ref grid y x) #\a) [dist (in-value (hash-ref a (cons x y)))] #:unless (= +inf.0 dist)) dist))) (define (parse fname) (define grid (for/vector ([line (in-list (file->lines fname))]) (list->vector (string->list line)))) (define (valid-move? a b) (define (hm->int x) (char->integer (match x [#\S #\a] [#\E #\z] [_ x]))) (<= (hm->int b) (add1 (hm->int a)))) (define edges (for*/fold ([edges '()]) ([y (in-range (grid-h grid))] [x (in-range (grid-w grid))] [neigh (in-list (list (cons (add1 x) y) (cons (sub1 x) y) (cons x (add1 y)) (cons x (sub1 y))))] #:when (< -1 (car neigh) (grid-w grid)) #:when (< -1 (cdr neigh) (grid-h grid))) (define this-val (grid-ref grid y x)) (define neigh-val (grid-ref grid (cdr neigh) (car neigh))) (if (valid-move? this-val neigh-val) (cons (list neigh (cons x y)) edges) edges))) (list grid (directed-graph edges))) (module+ main (define input (parse "inputs/12")) (answer 12 1 (time (part1 input))) (answer 12 2 (time (part2 input))) (displayln "meow"))