Lisp 如何使用最小冲突启发式避免陷入8皇后的局部极小值
我编写了以下代码来解决n皇后问题:Lisp 如何使用最小冲突启发式避免陷入8皇后的局部极小值,lisp,n-queens,simulated-annealing,Lisp,N Queens,Simulated Annealing,我编写了以下代码来解决n皇后问题: (defun solve (board max-steps) (enforce-one-queen-per-column board) (dotimes (step max-steps) ; repeat for a max amount of times, (if (eql (get-threatened-queens board) 0) ; if we have solved the board, return it
(defun solve (board max-steps)
(enforce-one-queen-per-column board)
(dotimes (step max-steps) ; repeat for a max amount of times,
(if (eql (get-threatened-queens board) 0) ; if we have solved the board, return it
(progn
(format t "Solved!")
(return board)
)
)
(let ((threatened-queens (get-threatened-queens board)) ; get all threatened queens
(queen nil))
(setf queen (nth (random (length threatened-queens)) threatened-queens)) ; choose random threatened queen
; find which row in its column where it would be least threatened
(let ((row-with-min-threats nil) ; (row_index, num_threats set to a high number)
(col (car queen))
(row (cdr queen)))
(format t "Dealing with threatened queen at (~A, ~A)...~%" col row)
(dotimes (i (array-dimension board 0)) ; for each row, find num of threats
(let ((num-threats (get-num-threats board col i)))
(print (car row-with-min-threats))
(format t "Checking (~A, ~A)~%" col i)
(format t "Threatened by ~A queens...~%" num-threats)
; if row-with-min-threats has not yet been initialized
; or if the row's threat is smaller than the tracked row with min threats
; take first row as min threat so far
(if (eql row-with-min-threats nil) ;
(setf row-with-min-threats (cons i num-threats))
(if (< num-threats (cdr row-with-min-threats)) ; if not first row and current min threats is smaller than tracked min
(setf row-with-min-threats (cons i num-threats))
(if (and (eql num-threats (cdr row-with-min-threats))
(eql (random 2) 1)) ; if current cell's & min cell's threats are equal, we randomly decide which cell to assign
(progn
(format t "Randomly chose (~A, ~A)...~%" col i)
(setf row-with-min-threats (cons i num-threats)))
)
)
)
)
)
(format t "Least threatened cell is (~A, ~A)...~%" col (car row-with-min-threats))
(if (not (eql row (car row-with-min-threats))) ; if its least threatened position isn't where it currently is
(progn
(setf (aref board (car row-with-min-threats) col) 1) ; move queen
(setf (aref board row col) 0)
(format t "Moved queen to (~A, ~A)...~%" col (car row-with-min-threats))
)
)
)
)
)
nil
)
其中,10表示原始板上调用solve
的次数
我没有包括我的功能,因为它们是不言自明的,但如果它们有帮助,我将很高兴包括它们
我试图通过重新启动原始板来克服这个问题,但无论我重新启动多少次,它似乎都不起作用,因为皇后们都被困在最小冲突点,即使它们仍然冲突
我相信这仅仅意味着你给出的初始位置根本无法通过启发式“修复”。在这种情况下,您需要一个新的“种子”,您可以通过在所有8列中随机选择一行来获得,然后这样做(如果结果是一个坏种子),直到获得一个好种子。由于解空间逐渐增大,在一个n*n板中,“n”越高,初始位置/种子的数量就越多 下面是一个Java类,其中包含以下注意事项(主要是main和shuffle方法): 我希望这能对你有所帮助。如果我有任何错误,欢迎批评
(setf board (make-board 8))
(solve board 10)