From 0758ee4e559a83fea7e1fc6611a22a1568ca63d6 Mon Sep 17 00:00:00 2001 From: Alex Karle Date: Tue, 13 Dec 2022 20:52:48 -0500 Subject: [PATCH] day12: Add part 2 solution --- 2022/12/sol.scm | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/2022/12/sol.scm b/2022/12/sol.scm index 99d258b..ae39d4a 100755 --- a/2022/12/sol.scm +++ b/2022/12/sol.scm @@ -37,7 +37,7 @@ (define (ident x) x) -(define (neigh grid pos) +(define (neigh grid pos dir) (define (in-bounds? pt) (let ((n (vector-length grid)) (m (vector-length (vector-ref grid 0)))) @@ -53,7 +53,9 @@ (j2 (caddr pt)) (l1 (get grid i j)) (l2 (get grid i2 j2))) - (and (<= l2 (add1 l1))))) + (if (eq? dir 'up) + (and (<= l2 (add1 l1))) + (and (>= (add1 l2) l1))))) (let* ((d (car pos)) (i (cadr pos)) (j (caddr pos))) @@ -75,7 +77,24 @@ (if (equal? (cdr pos) goal) (car pos) (let ((neighs (filter (lambda (p) (not (hash-table-exists? seen (cdr p)))) - (neigh grid pos)))) + (neigh grid pos 'up)))) + (for-each (lambda (p) (hash-table-set! seen (cdr p) 1)) neighs) + (loop (append (cdr Q) neighs))))))))) + +;; Part 2 is a simple flip of the search: don't search for one goal loc +;; search starting at E and until depth 0 (with inverted 'in-reach?) +(define (dist-down grid start) + ;; BFS to find the goal, each item is (D i j) where D is depth + (let ((seen (make-hash-table))) + (let loop ((Q (list (cons 0 start)))) + (if (null? Q) + #f + (let ((pos (car Q))) + (hash-table-set! seen (cdr pos) 'seen) + (if (equal? (get grid (cadr pos) (caddr pos)) 0) + (car pos) + (let ((neighs (filter (lambda (p) (not (hash-table-exists? seen (cdr p)))) + (neigh grid pos 'down)))) (for-each (lambda (p) (hash-table-set! seen (cdr p) 1)) neighs) (loop (append (cdr Q) neighs))))))))) @@ -86,7 +105,8 @@ (lgrid (make-grid lines lvl)) (start (find cgrid #\S)) (goal (find cgrid #\E))) - (print (dist lgrid start goal)))) + (print (dist lgrid start goal)) + (print (dist-down lgrid goal)))) ; for repl (define ln '("Sabqponm" -- libgit2 1.8.1