I've recently picked up prolog and am trying to make a program to find a solution for the famous puzzle Knight's Tour [found here]
Using the Warnsdorff algorithm i'm trying to find all the possible moves that can be made from a specific spot on the chess board and then make the move that has the least possible moves once it's made and then repeat the process, however I am having trouble finding said move.
Here is my code so far
possibleKnightMove(I, J, I1, J1) :- I1 is I+1, J1 is J+2.
possibleKnightMove(I, J, I1, J1) :- I1 is I+2, J1 is J+1.
possibleKnightMove(I, J, I1, J1) :- I1 is I+2, J1 is J-1.
possibleKnightMove(I, J, I1, J1) :- I1 is I+1, J1 is J-2.
possibleKnightMove(I, J, I1, J1) :- I1 is I-1, J1 is J-2.
possibleKnightMove(I, J, I1, J1) :- I1 is I-2, J1 is J+1.
possibleKnightMove(I, J, I1, J1) :- I1 is I-2, J1 is J-1.
possibleKnightMove(I, J, I1, J1) :- I1 is I-1, J1 is J+2.
possible_knight_moves(Rows, Columns, X, Y, Visited, NewX, NewY) :-
possibleKnightMove(X, Y, NewX, NewY),
NewX > 0, NewX =< Rows,
NewY > 0, NewY =< Columns,
\+ member([NewX,NewY], Visited).
possible_moves_count(Rows, Columns, X, Y, Visited, Count) :-
findall(_, possible_knight_moves(Rows, Columns, X, Y, Visited, _NewX, _NewY), Moves),
length(Moves, Count).
warnsdorff(Rows, Columns, X, Y, Visited, NewX, NewY, Score) :-
possible_knight_moves(Rows, Columns, X, Y, Visited, NewX, NewY),
possible_moves_count(Rows, Columns, NewX, NewY, [[NewX, NewY] | Visited], Score).
Since the number of possible moves is only counted after finding them all then my list is not sorted how I would need it to be.
for example with this input
warnsdorff(8,8,3,5,[[1,1],[2,3],[3,5]], NewX, NewY, Score).
the result should be
NewX = 4,
NewY = 7,
Score = 5
however I get
NewX = 1,
NewY = 4,
Score = 3
If anyone could help me get NewX
and NewY
with the minimum score that would be great