Monday, July 06, 2009

Eight queens problem in Lisp


(defun solve-n-queens (n)
  (let ((solutions nil))
    (defun solve-internal (board k)
      (if (eq k (- n 1))
        (dolist (x1 (solve board k))
          (push x1 solutions))
        (dolist (x2 (solve board k))
          (solve-internal x2 (+ k 1)))))
    (solve-internal (make-board n) 0)
    solutions))

(defun solve (board k)
  (let ((solutions nil))
    (dotimes (i (length board))
      (if (present? i k (get-safe-squares board))
          (push (place-queen (clone-board board) (list i k)) solutions)))
    solutions))

Helper procedures left as an exercise for the gentle reader.