Prolog显示路径

时间:2013-05-20 00:31:28

标签: prolog

我有以下简单的图表:

  

x< ---> y< ---> ž

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

path(Start,End,Path) :-           % path/3: there is a `Path` from `Start` to `End`
    path(Start,End,[Start],Path).

path(End,End,RPath,Path) :-       % internal helper predicate `path/4`
    reverse(RPath,Path).
path(Start,End,Visited,Path) :-
    edge(Start,Next),
    \+ memberchk(Next,Visited),
    path(Next,End,[Next|Visited],Path).

示例查询:

?- path(x,z,P).
P = [x, y, z] ;                   % works as expected
false.

?- path(z,x,P).                        
false.                            % unexpectedly fails!

如何才能使上述查询成功?

2 个答案:

答案 0 :(得分:1)

如果您想处理无向图表:

path(Start, End, Visited, Path) :-
    ( edge(Start, Next) ; edge(Next, Start) ),
    ...

答案 1 :(得分:1)

首先,我们通过定义谓词edge/2来记下已知事实:

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

然后我们将edge/2 path/4一起使用,如下所示:

?- path(edge,Path,x,z).              % one direction
  Path = [x,y,z]
; false.

?- path(edge,Path,z,x).              % other direction
  Path = [z,y,x]
; false.

以下非常一般的查询怎么样?什么是基于edge/2所有可能路径?

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