3

I have written in Prolog:

edge(x, y).
edge(y, t).
edge(t, z).
edge(y, z).
edge(x, z).
edge(z, x).

path(Start, End, Path) :-
   path3(Start, End, [Start], Path).

path3(End, End, RPath, Path) :-
   reverse(RPath, Path).
path3(A,B,Path,[B|Path]) :-
   edge(A,B),
   !.
path3(A, B, Done, Path) :-
   edge(A, Next),
   \+ memberchk(Next, Done),
   path3(Next, B, [Next|Done], Path).

Its taking care of cyclic graphs as well, I am getting an irregular output when I try to traverse same node from same node.

eg: path(x,x,P). expected output should be:

P = [x, z, t, y, x]
P = [x, z, y, x]
P = [x, z, x]

However, I am getting output:

p = [x]             ------------> wrong case
P = [x, z, t, y, x]
P = [x, z, y, x]
P = [x, z, x]

How can I get rid of this unwanted case. Thanks

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
aragorn ara
  • 165
  • 3
  • 14
  • 1
    The cut in your program is incorrect. To see this, try `path(x,Y,P)` where `Y` is a variable. – false Dec 03 '14 at 13:32

2 Answers2

3

We use path/4 together with edge/2:

?- path(edge,Path,x,Last), edge(Last,x).
  Last = z, Path = [x,y,t,z]
; Last = z, Path = [x,y,z]
; Last = z, Path = [x,z]
; false.

Alright! Above three answers are exactly what the OP wished for in the question.

Just for fun let's look at all possible paths based on edge/2!

?- path(edge,Path,From,To).
  From = To       , Path = [To]
; From = x, To = y, Path = [x,y]
; From = x, To = t, Path = [x,y,t]
; From = x, To = z, Path = [x,y,t,z]
; From = x, To = z, Path = [x,y,z]
; From = y, To = t, Path = [y,t]
; From = y, To = z, Path = [y,t,z]
; From = y, To = x, Path = [y,t,z,x]
; From = t, To = z, Path = [t,z]
; From = t, To = x, Path = [t,z,x]
; From = t, To = y, Path = [t,z,x,y]
; From = y, To = z, Path = [y,z]
; From = y, To = x, Path = [y,z,x]
; From = x, To = z, Path = [x,z]
; From = z, To = x, Path = [z,x]
; From = z, To = y, Path = [z,x,y]
; From = z, To = t, Path = [z,x,y,t]
; false.
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166
0
path(Start, End, Path) :-
    edge(Start,First),
    path3(Start, End, [Start,First], Path).

should work

CapelliC
  • 59,646
  • 5
  • 47
  • 90