使用Prolog进行图路径搜索(含循环路径)

3

我在Prolog方面是个完全的新手。我正在尝试解决一个问题,需要检查边之间是否存在路径。我已经完成了非循环图代码,但对于循环图,我的代码会陷入无限循环。

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

我需要通过定义一个新的谓词来处理这个案例:new_path(Start,End,path),以消除无限循环。请告诉我如何进行。

2个回答

1

嘿,谢谢,但是能否不使用闭包0来完成,而是像路径一样定义自己的函数对象。再次感谢您的建议。 - aragorn ara

1
你需要在遍历过程中记录已访问的节点,使用 Prolog 列表作为一个 LIFO 栈。大致如下所示:
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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接