Prolog. Construct a transitive closure of a graph

喜夏-厌秋 提交于 2020-12-12 05:09:32

问题


I'm very new to Prolog. I have such a graph:

edge(a,e).
edge(e,f).
edge(f,d).
edge(d,a).

I define a transitive closure as:

p(X,Y) :- edge(X,Y).
tran(X,Z) :- p(X,Y), p(Y,Z).

I need to construct a transitive closure of a graph. Please let me know how to proceed with it.


回答1:


The problem with trans/2 is that it will only walk two edges, not an arbitrary number.

We can define a predicate tran(X, Z) that holds if edge(X, Z) holds, or edge(X, Y) and then tran(Y, Z). We thus in the latter follow one edge and then recurse on tran/2:

tran(X, Z) :-
    edge(X, Z).
tran(X, Z) :-
    edge(X, Y),
    tran(Y, Z).


来源:https://stackoverflow.com/questions/65063263/prolog-construct-a-transitive-closure-of-a-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!