Three-way matrix navigation
This commit is contained in:
parent
56ac4d366a
commit
9ff0334dd1
|
@ -0,0 +1,29 @@
|
|||
(defparameter *matrix* (read-matrix-from-file "0082_matrix.txt"))
|
||||
|
||||
(defparameter *directions* '((1 0)
|
||||
(0 1)
|
||||
(-1 0)))
|
||||
|
||||
(defun path-sum-three-ways ()
|
||||
(let* ((dimensions (array-dimensions *matrix*))
|
||||
(goal-column (1- (second dimensions)))
|
||||
(states (loop for r from 0 below (first dimensions)
|
||||
collect (cons (list r 0)
|
||||
(aref *matrix* r 0))))
|
||||
(visited (make-hash-table :test 'equal)))
|
||||
(loop with sums = nil
|
||||
for state = (pop states)
|
||||
while state
|
||||
do (destructuring-bind (position . sum) state
|
||||
(setf (gethash position visited) t)
|
||||
(when (= (second position) goal-column)
|
||||
(push sum sums))
|
||||
(loop for offset in *directions*
|
||||
for new-position = (mapcar #'+ position offset)
|
||||
when (and (every #'in-bounds-p new-position dimensions)
|
||||
(not (gethash new-position visited)))
|
||||
do (push (cons new-position
|
||||
(+ sum (apply #'aref (cons *matrix* new-position))))
|
||||
states))
|
||||
(setf states (sort states #'< :key #'cdr)))
|
||||
finally (return (apply #'min sums)))))
|
Loading…
Reference in New Issue