:- use_module(library(lists),[member/2]). path([StartPoint|RestPath]) :- StartPoint = (1,1), Visited = [StartPoint], complete_path(1,1,Visited,RestPath). complete_path(I,J,_,ResultPath) :- goto(I,J,final), !, ResultPath = []. complete_path(I,J,Visited,ResultPath) :- ( goto(I,J,Direction) -> true ; true ), next_square(Direction,I,J,NewI,NewJ), \+ bad_move(NewI,NewJ,Visited), ResultPath = [(NewI,NewJ)|TailResultPath], complete_path(NewI,NewJ,[(NewI,NewJ)|Visited],TailResultPath). bad_move(I,J,Visited) :- member((I,J),Visited). bad_move(I,J, _) :- (I < 1 ; J < 1). bad_move(I,J, _) :- size(N), (I > N ; J > N). next_square( up, I,J, I,NewJ) :- NewJ is J + 1. next_square( down, I,J, I,NewJ) :- NewJ is J - 1. next_square( left, I,J, NewI, J) :- NewI is I - 1. next_square(right, I,J, NewI, J) :- NewI is I + 1.