Can not get first node in the visited nodes of prolog graph traversal

Viewed 53

I found a path finding algorithm based on Prolog.

This is the content of the graph_traversal.P file.

path(X,Y,P) :- path_aux(X,Y,[Y],P).
path_aux(X,Y,L,[X|L]) :- arc(X,Y).
path_aux(X,Y,L,P) :- arc(Z,Y), not(member(Z,L)), path_aux(X,Z,[Z|L],P).

I provide a list of arcs in the form of pairs. When I query this using below lines

command = "path(" + start + "," + end+ ", P)"
for item in prolog.query(command):
  print("item", item)

I get something like this in the item var

Start: Middle0, [Middle1, Middle 2, ..., End]

I expect to have something like this

[Start, Middle0, Middle1, Middle 2, ..., End]

I do not know Prolog but I have to solve this problem. Can you please help me to solve this?

1 Answers

The lines below solved the problem.

path(A,B,Path) :- 
   travel(A,B,[A],Q), 
   reverse(Q,Path).

travel(A,B,P,[B|P]) :- 
   arc(A,B).
travel(A,B,Visited,Path) :- 
   arc(A,C), 
   C \== B, 
   \+member(C,Visited), 
   travel(C,B,[C|Visited],Path).
Related