如何检查房间之间的路径是否连接

时间:2014-11-11 02:49:57

标签: prolog transitive-closure

我有以下事实构建我的地牢的翅膀。

path(room1,e,room2).
path(room2,w,room1).
path(room2,e,room5).
path(room5,w,room2).
path(room5,e,room6).
path(room6,w,room5).
path(room2,n,room3).
path(room3,s,room2).
path(room3,e,room4).
path(room4,w,room3).
path(room4,s,room5).
path(room5,n,room4).
path(room5,s,room7).
path(room7,n,room5).
path(room7,e,room8) :- at(key, in_hand).
path(room7,e,room8) :- write('The door appears to be locked.'), nl, fail.
path(room8,w,room7).
path(room2,s,room9).
path(room9,n,room2).
path(room9,s,room10).
path(room10,n,room9).
path(room10,w,room11).
path(room11,e,room10).
path(room11,s,room12).
path(room12,n,room11).

现在我想检查一个房间是否连接到另一个房间,然后可能显示其中一个可能的路径。  我试着这样做 connected(X,Y):-path(X,_,Z),path(Z,_,Y). 但它一直让我虚假,我做错了什么。

1 个答案:

答案 0 :(得分:0)

尝试类似

的内容
connect(Bgn,End,Path) :-    % to find a path between two nodes in the graph
  connected(Bgn,End,[],P) , % - we invoke the helper, seeding the visited list as the empty list
  reverse(P,Path)           % - on success, since the path built has stack semantics, we need to reverse it, unifying it with the result
  .

connected(X,Y,V,[X,Y|V]) :- % can we get directly from X to Y?
  path(X,_,Y)               % - if so, we succeed, marking X and Y as visited
  .                         %
connected(X,Y,V,P) :-       % otherwise...
  path(X,_,T) ,             % - if a path exists from X to another room (T)
  T \= Y ,                  % - such that T is not Y
  \+ member(X,V) ,          % - and we have not yet visited X
  connected(T,Y,[X|V],P)    % - we continue on, marking X as visited.
  .

你会注意到以前去过房间的测试。如果您的图表有周期,如果您之前没有对某个节点进行过某种测试,那么您将会绕圈子四处走动......直到出现堆栈溢出。

相关问题