common lisp - How do you print only the first solution of backtracking? -
i working on n-queens problem using backtracking in lisp. far, code prints possible solutions n>=4. however, wish print first solution value of n.
(defun backtracksearch (row n) // (if () *i need line here stop once first solution found* (if (< row n) (loop j below n (when (is-safe row j n) (setf (aref *chessboard* row j) 'board) (backtracksearch (+ 1 row) n) (setf (aref *chessboard* row j) 'nil))) (print-solution n)))
i have tried use same implementation/logic in c++ solution of backtracking n-queens. advice on possible way forward helpful.
some feedback on code:
it badly formatted, indent follows:
(defun backtracksearch (row n) (if (< row n) (loop j below n (when (is-safe row j n) (setf (aref *chessboard* row j) 'board) (backtracksearch (+ 1 row) n) (setf (aref *chessboard* row j) 'nil))) (print-solution n)))
//
comments in c++, use;
instead(dotimes (j n) (when ...))
sufficient.
some questions find solution:
- what happens when there no
j
satisfyingis-safe
? - in particular, return value of
backstracksearch
? - what return value when find solution?
- how determine if recursive call
backtracksearch
found solution? - could use information avoid computing other solutions?
Comments
Post a Comment