Gprolog Knight's Tour using Warnsdorff's Rule

余生颓废 提交于 2019-12-24 02:14:15

问题


I'm trying to implement Warnsdorff's Rule in Gprolog to generate tours on an arbitrary chessboard. I found an SO post providing a good solution in B-prolog, and I simply needed to translate the Warnsdorff step (knight's tour efficient solution).

Below is my implementation of the Warnsdorff step:

warnsdorffSelect(X, Y, Row, Col, Past, NewX_, NewY_) :-
  setof((Count, NewX, NewY), (
    possibleMovesFromPosWithBoard(X, Y, Row, Col, Past, NewX, NewY),
    countMoves(NewX, NewY, Row, Col, [(NewX, NewY) | Past], Count).
  ), [(_, NewX_, NewY_)|_]).

possibleMovesFromPosWithBoard/7 returns all legal moves from a position and countMoves/6 returns the number of moves from a position.

My problem happens when the function fails to select the move that results in the lowest number of moves from the new position and instead opts to return the first move in the resulting list (that is to say, it doesn't appear to be sorting). In the end the program always results in 'no' because it backs itself into a corner.

Thanks in advance!


回答1:


The full search space is easily recovered:

warnsdorffSelect(X, Y, Row, Col, Past, NewX_, NewY_) :-
  setof((Count, NewX, NewY), (
    possibleMovesFromPosWithBoard(X, Y, Row, Col, Past, NewX, NewY),
    countMoves(NewX, NewY, Row, Col, [(NewX, NewY) | Past], Count).
  ), Sorted),
  % on backtracking, get all steps sorted from lower Count to higher
  member((_, NewX_, NewY_), Sorted).


来源:https://stackoverflow.com/questions/43622353/gprolog-knights-tour-using-warnsdorffs-rule

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!