Advertisement
Guest User

A Toy Maze Solver

a guest
Feb 2nd, 2011
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 2.26 KB | None | 0 0
  1. ;;;; -*- coding: utf-8 -*-
  2.  
  3. (defparameter *maze-image*
  4.   (make-array '(8 8) :initial-contents
  5.               '((1 1 1 1 1 1 1 1)
  6.                 (1 0 1 0 1 1 0 1)
  7.                 (1 0 1 0 1 0 0 1)
  8.                 (1 0 0 0 1 1 0 1)
  9.                 (1 1 1 0 0 0 0 1)
  10.                 (1 0 1 0 1 1 0 1)
  11.                 (1 0 0 0 0 1 0 1)
  12.                 (1 1 1 1 1 1 1 1))))
  13.  
  14. (defun is-passage (maze-image x y)
  15.   (= (aref maze-image y x) 0))
  16.  
  17. (defun make-maze-map (maze-image)
  18.   (let ((result '()))
  19.     (loop :for y :from 1 :to 6 :do
  20.        (loop :for x :from 1 :to 6 :do
  21.           (when (is-passage maze-image x y)
  22.             (let ((position (list x y nil))
  23.                   (movable-positions '()))
  24.               (loop :for (dx dy) :in '((0 -1) (1 0) (0 1) (-1 0)) :do
  25.                  (when (is-passage maze-image (+ x dx) (+ y dy))
  26.                    (push (list (+ x dx) (+ y dy)) movable-positions)))
  27.  
  28.               (push (list position movable-positions) result)))))
  29.     (reverse result)))
  30.  
  31.  
  32. (defun get-movable-positions (maze-map current-position)
  33.     (let ((result nil))
  34.       (dolist (candidate-position
  35.                 (cadr (assoc `(,@current-position t) maze-map :test #'equal)))
  36.         (if (assoc `(,@candidate-position nil) maze-map :test #'equal)
  37.             (push candidate-position result)))
  38.       result))
  39.  
  40.  
  41. (defun set-passed-mark (maze-map position)
  42.   (setf (caddr (car (assoc `(,@position nil) maze-map :test #'equal))) t))
  43.  
  44.  
  45. (let ((maze-map (make-maze-map *maze-image*)))
  46.   (defun walk-maze (current-position goal)
  47.     (format t "curpos : ~a~%" current-position)
  48.     (set-passed-mark maze-map current-position)
  49.     (if (equal current-position goal)
  50.         (list goal)
  51.         (let ((movable-positions (get-movable-positions maze-map current-position)))
  52.           (format t "movable : ~a~%" movable-positions)
  53.           (cond (movable-positions
  54.                  (dolist (next-position movable-positions)
  55.                    (let ((move-result (solve-maze next-position goal)))
  56.                      (cond (move-result
  57.                             (return (append (list current-position) move-result)))
  58.                            (t nil)))))
  59.                 (t nil)))) ))
  60.  
  61.  
  62. (defun solve-maze (start goal)
  63.   (walk-maze start goal))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement