:- op(700, xfx, l). :- op(700, xfx, r). From l To :- From to To-_. From r To :- From to _-To. answer(Answer) :- starts(Starts), path([], Starts, Answer). path(_, EndNodes, []) :- all_ends(EndNodes), !. path(Directions, FromList, Moves) :- next_step(Directions, Move, Remain), maplist(Move, FromList, ToList), path(Remain, ToList, RemainingMoves), Moves is RemainingMoves + 1. next_step([Move | Remain], Move, Remain). next_step([], Move, Remain) :- direction(Str), atom_chars(Str, [Move | Remain]). starts(StartNodes) :- findall(Node, Node to _, Nodes), include(is_start, Nodes, StartNodes). all_ends(Nodes) :- maplist(is_end, Nodes). is_start(Node) :- atom_chars(Node, [_, _, a]). is_end(Node) :- atom_chars(Node, [_, _, z]).