I'm trying to write a Prolog program to give me all possible paths between two points in a graph (with cycle).
edge(a,b).
edge(a,c).
edge(a,d).
edge(b,e).
edge(c,e).
edge(c,f).
edge(d,f).
edge(f,g).
edge(g,e).
edge(e,a).
show_path(X,Y,[X,Y]) :- edge(X,Y).
show_path(X,Z,[X|T]) :- edge(X,Y), not(member(Y, T)), show_path(Y,Z,T).
I'm trying to use not(member())
to exclude the cycles and avoid infinite loop but it doesn't yield all possible solutions. How can I alter the program to get the all possible paths between two points in a graph with cycle?
Your program does not work because
not(member(Y, T))
will always be false: at this point,T
is not instantiated so it's always possible to find a list which containsY
.You can fix your program by adding an accumulator:
It's not clear what you mean by avoiding cycles. Here, it will avoid passing twice on the same point, unlike @coder's answer. For example:
You can easily see that
not(member(Y, T))
fails when T is not instantiated. For example try:where you see that it fails. To solve that you need to keep an extra list that will be instantiated in every step beginning with empty list:
Example:
You could have the output that @Fatalize suggested also by writing:
Example: