在图表中查找路线

时间:2014-05-16 02:37:36

标签: graph prolog

我正在尝试找到所有可能的路线,然后打印给用户,但由于我对prolog很新,我遇到了一些麻烦。

graph http://i62.tinypic.com/11tu1sh.png

我必须打印所有可能的方法从A到G。这是我到目前为止:

direct_path(pathA,pathB).
direct_path(pathA,pathC).
direct_path(pathB,pathD).
direct_path(pathC,pathE).
direct_path(pathC,pathF).
direct_path(pathE,pathD).
direct_path(pathE,pathG).
direct_path(pathF,pathG).

upward(X, Y):- direct_path(X, Y).
upward(X, Z):- direct_path(X, Y), upward(Y, Z).

这样我可以检查是否可以从A到G,但是如何打印这条路径呢?

1 个答案:

答案 0 :(得分:4)

只需在upward谓词中添加第三个参数即可存储路径:

upward(X, Y, [X, Y]):- direct_path(X, Y).
upward(X, Z, [X | Rest]):- direct_path(X, Y), upward(Y, Z, Rest).

试运行:

?- upward(pathA, pathG, Path).
Path = [pathA, pathC, pathE, pathG] ;
Path = [pathA, pathC, pathF, pathG] ;
false.

因此从A到G有两条不同的路径。