home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / xl21hos2.zip / QUEENS.LSP < prev    next >
Lisp/Scheme  |  1995-12-27  |  1KB  |  46 lines

  1. ;
  2. ; Place n queens on a board
  3. ;  See Winston and Horn Ch. 11
  4. ; Usage:
  5. ;    (queens <n>)
  6. ;          where <n> is an integer -- the size of the board - try (queens 4)
  7.  
  8. ; Do two queens threaten each other ?
  9. (defun threat (i j a b)
  10.   (or (eql i a)            ;Same row
  11.       (eql j b)            ;Same column
  12.       (eql (- i j) (- a b))    ;One diag.
  13.       (eql (+ i j) (+ a b))))    ;the other diagonal
  14.  
  15. ; Is position (n,m) on the board not safe for a queen ?
  16. (defun conflict (n m board)
  17.   (cond ((null board) nil)
  18.     ((threat n m (caar board) (cadar board)) t)
  19.     (t (conflict n m (cdr board)))))
  20.  
  21.  
  22. ; Place queens on a board of size SIZE
  23. (defun queens (size)
  24.   (prog (board n m)
  25.     (setq board nil)
  26.     (setq n 1)            ;Try the first row
  27.     loop-n
  28.     (setq m 1)            ;Column 1
  29.     loop-m
  30.     (cond ((conflict n m board) (go un-do-m))) ;Check for conflict
  31.     (setq board (cons (list n m) board))       ; Add queen to board
  32.     (cond ((> (setq n (1+ n)) size)            ; Placed N queens ?
  33.            (print (reverse board))))           ; Print config
  34.     (go loop-n)                       ; Next row which column?
  35.     un-do-n
  36.     (cond ((null board) (return 'Done))        ; Tried all possibilities
  37.           (t (setq m (cadar board))           ; No, Undo last queen placed
  38.          (setq n (caar board))
  39.          (setq board (cdr board))))
  40.  
  41.     un-do-m
  42.     (cond ((> (setq m (1+ m)) size)          ; Go try next column
  43.            (go un-do-n))
  44.           (t (go loop-m)))))
  45.