从Prolog中的递归谓词返回列表

时间:2017-08-29 15:22:33

标签: list recursion prolog undirected-graph

我编写了一个名为find_path(S,T,Visited,Path)的谓词,它可以搜索我的无向图并找到从节点S到节点T的路径,然后返回一个边缘值列表(边缘值是边缘的第3个值)事实)。我写的谓词似乎工作正常,但它只返回搜索结果的布尔值,没有边值列表。有人可以提出一个如何实现这一目标的建议吗?提前谢谢。

这是我的代码和我正在使用的无向图的图像

enter image description here

find_path(S,T,Visited,Path) :-
    not(member(S,Visited)),         % Check that S hasnt already been visited
    direct_path(S,T,edge(S,T,D))    % Check if theres a direct path from S to T.
    ->  append(Path,[D],X)          % If so, append the edge value to Path list and end
    ;   append(Visited,[S],Y),          % If not, add S to Visited
        direct_path(S,A,edge(S,A,B)),   %   Find any edge containing S
        append(Path,[D],X),             %   Add the edge value to the path list
        find_path(A,T,Y,X).             %   Recursively call find_path again, with the new Start value

direct_path(S,T,edge(S,T,D)) :- edge(S,T,D); edge(T,S,D).

edge(1,2,7). 
edge(1,3,9). 
edge(1,6,14). 
edge(2,3,10). 
edge(2,4,15). 
edge(3,4,11). 
edge(3,6,2). 
edge(4,5,6). 
edge(5,6,9).

0 个答案:

没有答案