Skip to content

Instantly share code, notes, and snippets.

@nomnel
Created July 5, 2012 12:28
Show Gist options
  • Save nomnel/3053429 to your computer and use it in GitHub Desktop.
Save nomnel/3053429 to your computer and use it in GitHub Desktop.
一般のNに対してN-queen問題を解くやつ
; (N-queen 7 '((2 3) (4 6))) => ((7 7) (6 2) (5 4) (3 1) (1 5) (2 3) (4 6))
(define (N-queen N ini-points)
(define (delete-l lst target)
(if (null? lst) target
(delete-l (cdr lst) (delete (car lst) target))))
(define (ok? x y his)
(let loop ((his his))
(cond ((null? his) #t)
((= (abs (- x (caar his)))
(abs (- y (cadar his))))
#f)
(else (loop (cdr his))))))
(call/cc
(^(return)
(let loop ((xs (delete-l (map car ini-points) (iota N 1)))
(ys (delete-l (map cadr ini-points) (iota N 1)))
(result ini-points))
(if (null? xs) (return result)
(dolist (y ys)
(when (ok? (car xs) y result)
(loop (cdr xs) (delete y ys) (cons `(,(car xs) ,y) result)))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment