Graph path define issue

2019-08-05 14:27发布

The solution

ppath(X,Y,M,Path,[Y|Path]) :- edge(X,Y,M),\+ memberchk(Y,Path).
path(X,Y,P,SoFar,Path) :- edge(X,W,M), \+ memberchk(W,SoFar),
    path(W,Y,N,[W|SoFar],Path), P is M+N.
 pravilo(X,Y,Z) :-
    aggregate(min(W), P^path(X,Y,W,[],P),Z).

Here is the code i have. The question is that starting point is a, and ending point is z.

There is an error after execution, the result is displayed like [z, c, h, b]. But the correct answer should [a,b,c,z].

Please help to fix my problem.

1条回答
在下西门庆
2楼-- · 2019-08-05 15:22

library(aggregate) allows for a witness on min/max scalar operations. We can use that feature to report back the path as well as the travel length:

path(X,Y,M,Path,FullPath) :-
    edge(X,Y,M), \+ memberchk(Y,Path),
    reverse([Y|Path], FullPath).
path(X,Y,P,SoFar,Path) :-
    edge(X,W,M), \+ memberchk(W,SoFar),
    path(W,Y,N,[W|SoFar],Path), P is M+N.

pravilo(X,Y,Z,Path) :-
    aggregate(min(W,P), P^path(X,Y,W,[X],P), min(Z,Path)).

Note there is a typo in edge/3: edge(b,e,16 should be edge(b,e,16)..

Once corrected the DB, I get

pravilo(a,z,M,P).
M = 16,
P = [a, b, h, c, z].
查看更多
登录 后发表回答