I want to find the shortest path between two nodes in Prolog. I figured how to find all the paths between two nodes, but unfortunately the following code falls into loops:
arc(a,b).
arc(b,a).
arc(b,c).
arc(c,b).
arc(c,d).
arc(d,c).
path(X,Y,[arc(X,Y)]) :-
arc(X,Y).
path(X,Y,[arc(X,Z)|P]) :-
arc(X,Z),
path(Z,Y,P).
The code run is:
?- path(a,c,R).
R = [arc(a, b), arc(b, c)] ;
R = [arc(a, b), arc(b, a), arc(a, b), arc(b, c)] ;
R = [arc(a, b), arc(b, a), arc(a, b), arc(b, a), arc(a, b), arc(b, c)]
....
So, my question is : How to get all paths without looping infinitely?
at the end of the day, i will get the length of the list and find the minimum.
Please if possible, give solutions that are ISO Prolog.
Note: here is the updated code, by I still have problem. Apparently the member predicate doesn't work when checking against a fact rather than an atom.
xxx([]).
path(X,Y,[arc(X,Y)]) :-
arc(X,Y).
path(X,Y,[arc(X,Z)|P]) :-
arc(X,Z)
,xxx(L)
,member(arc(X,Z),L)->
!;
(member(arc(Z,X),L)->
!;
(append(L,[arc(X,Z)],R),retract(xxx(_)),assert(xxx(R)),path(Z,Y,P))).
and my member predicate is:
member(X,[X|T]).
member(X,[H|T]) :- member(X,T).
Thank you.