如何在Prolog图遍历中处理路径

时间:2014-12-03 06:07:39

标签: graph prolog traversal cyclic-graph

我用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).

它也处理循环图,当我尝试从同一节点遍历同一节点时,我得到一个不规则的输出。

例如:path(x,x,P). 预期产出应为:

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

但是,我得到了输出:

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

如何摆脱这种不必要的情况。 感谢

2 个答案:

答案 0 :(得分:1)

我们将 path/4edge/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.

好吧!以上三个答案正是OP在问题中所希望的。

为了好玩,让我们根据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.

答案 1 :(得分:0)

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

应该有效