Skip to content

Instantly share code, notes, and snippets.

@kyontan
Created June 5, 2017 13:13
Show Gist options
  • Save kyontan/9d3b437b4675c420813d74cf5e603a41 to your computer and use it in GitHub Desktop.
Save kyontan/9d3b437b4675c420813d74cf5e603a41 to your computer and use it in GitHub Desktop.
n-queen problem in Common LISP
(defun can-place (x y queens)
(cond
((member t (mapcar #'(lambda (xy) (or (= x (car xy)) (= y (cadr xy)))) queens)) nil)
((member t (mapcar #'(lambda (xy) (= 1 (abs (/ (- x (car xy)) (- y (cadr xy)))))) queens)) nil)
(t)))
; try putting a queen to (x y);
; if possible, put it and try putting recursively
; otherwise, trying putting a queen in order: (1 1) ~ (max max)
(defun solve-loop (x y queens max)
(cond
((= max (length queens)) (print (list 'answer queens)) (cdr queens)) ; print answer and backtrack (try to solve more than 1 answer)
; ((= max (length queens)) queens)
((or (> x max) (> y max)) (cdr queens)) ; backtrack
((can-place x y queens)
(setq rec (solve-loop (+ 1 x) 1 (append (list (list x y)) queens) max))
(cond
((equal queens rec) (solve-loop x (+ 1 y) queens max)) ; backtracked
(t rec)))
(t (solve-loop x (+ 1 y) queens max))))
; (trace solve-loop)
(defun solve (max queens)
(solve-loop 1 1 queens max))
(print (list 'answer (solve 8 '()))) ; try 8 queen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment