Skip to content

Commit 53244a7

Browse files
committed
CLisp: NQueen
1 parent 5670ef6 commit 53244a7

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

BackTracking/NQueens/nqueen.lisp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
(setq N 6)
2+
(setq rows (make-array N))
3+
(setq cols (make-array N))
4+
(setq diag1 (make-array (+ N N 1)))
5+
(setq diag2 (make-array (+ N N 1)))
6+
7+
(defun print-board()
8+
(format t "~%")
9+
(loop for i from 0 to (- N 1) do
10+
(format t "~%")
11+
(loop for j from 0 to (- N 1) do
12+
(cond
13+
((eq (aref rows i) j) (prin1 'Q))
14+
(t (prin1 '-))
15+
)
16+
)
17+
)
18+
)
19+
20+
(defun rec(j)
21+
(when (>= j N) (print-board) (return-from rec))
22+
(loop for i from 0 to (- N 1) do
23+
(let ((x (+ (- i j 1) N)) (y (- (+ N N) i j)))
24+
(when (and (null (aref rows i)) (null (aref diag1 x)) (null (aref diag2 y)))
25+
(setf (aref cols j) j)
26+
(setf (aref rows i) j)
27+
(setf (aref diag1 x) j)
28+
(setf (aref diag2 y) j)
29+
(rec (+ j 1))
30+
(setf (aref cols j) nil)
31+
(setf (aref rows i) nil)
32+
(setf (aref diag1 x) nil)
33+
(setf (aref diag2 y) nil)
34+
)
35+
)
36+
)
37+
)
38+
39+
; (print-board)
40+
(rec 0)

0 commit comments

Comments
 (0)