Path 具有循环路径的Prolog图路径搜索

Path 具有循环路径的Prolog图路径搜索,path,prolog,infinite-loop,transitive-closure,cyclic-graph,Path,Prolog,Infinite Loop,Transitive Closure,Cyclic Graph,我在Prolog中是一个完全的新手。我试图找出一个问题,我需要检查边之间是否存在路径。我已经完成了循环的无环图代码,我的代码将进入无限循环 path(Start, End) :- edge(Start, End). path(Start, End) :- edge(Start, Z), path(Z, End). 我需要通过定义一个新谓词来处理这种情况: 新路径(开始、结束、路径) 这将消除无限循环。请告诉我如何进行 试试看 path(Start, End) :- closure(edg

我在Prolog中是一个完全的新手。我试图找出一个问题,我需要检查边之间是否存在路径。我已经完成了循环的无环图代码,我的代码将进入无限循环

path(Start, End) :- edge(Start, End).
path(Start, End) :- edge(Start, Z), path(Z, End).
我需要通过定义一个新谓词来处理这种情况: 新路径(开始、结束、路径) 这将消除无限循环。请告诉我如何进行

试试看

path(Start, End) :-
   closure(edge, Start, End).

使用

您需要在运行过程中跟踪您访问过的节点,使用prolog列表作为后进先出堆栈。大致如下:

path( A , Z , P ) :-           % to find a path from A to Z
  traverse( A , Z , [] , P ) , % take a walk, visiting A to see if we can get to Z, seeding the visited list with the empty string.
  reverse(P,Path)              % once we find a path, let's reverse it, since it's in LIFO order.
  .                            % That's all there is to it, really.

traverse( Z , Z , V , [Z|V] )     % if current node is the destination node, we've arrived.
  .                               % - just push the destination vertice onto the visited list and unify that with the path
traverse( A , Z , V , P ) :-      % Otherwise...
  edge( A , Z ) ,                 % - if the current node is directly connected to the destination node,
  traverse( Z , Z , [A|V] , P)    % - go visit the destination, marking the current node as visited
  .                               %
traverse( A, Z , V , P ) :-       % Otherwise...
  A \= Z,
  edge( A , B ) ,                 % - if the current node is connected to a node
  B \= Z ,                        % - that is not the destination node, and
  unvisited([A|V],B) ,            % - we have not yet visited that node,
  traverse( B , Z , [A|V] , P )   % - go visit the intermediate node, marking the current node as visited.
  .                               % Easy!

unvisited( []    , _ ) .                   % We succeed if the visited list is empty.
unvisited( [A|_] , A ) :- ! , fail .       % We fail deterministically if we find the node in the visited list.
unvisited( [_|L] , A ) :- unvisited(L,A) . % otherwise, we keep looking.

嘿,谢谢,但是在没有closure0的情况下,我可以定义我自己的仿函数路径吗。再次感谢您的投入。