-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
nqueen.lisp
40 lines (37 loc) · 929 Bytes
/
nqueen.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
(setq N 6)
(setq rows (make-array N))
(setq cols (make-array N))
(setq diag1 (make-array (+ N N 1)))
(setq diag2 (make-array (+ N N 1)))
(defun print-board()
(format t "~%")
(loop for i from 0 to (- N 1) do
(format t "~%")
(loop for j from 0 to (- N 1) do
(cond
((eq (aref rows i) j) (prin1 'Q))
(t (prin1 '-))
)
)
)
)
(defun rec(j)
(when (>= j N) (print-board) (return-from rec))
(loop for i from 0 to (- N 1) do
(let ((x (+ (- i j 1) N)) (y (- (+ N N) i j)))
(when (and (null (aref rows i)) (null (aref diag1 x)) (null (aref diag2 y)))
(setf (aref cols j) j)
(setf (aref rows i) j)
(setf (aref diag1 x) j)
(setf (aref diag2 y) j)
(rec (+ j 1))
(setf (aref cols j) nil)
(setf (aref rows i) nil)
(setf (aref diag1 x) nil)
(setf (aref diag2 y) nil)
)
)
)
)
; (print-board)
(rec 0)