SWI-Prolog で、あるノードから次のノードへ有向グラフを実行する簡単なプログラムを作成しています。ただし、サイクルを回避するのに問題があり、助けが必要です。各エッジにはコストが関連付けられており、各ノードには「滞在時間」があります。
edge(a, b, 10).
edge(a, c, 20).
edge(c, d, 50).
edge(c, b, 40).
edge(d, b, 30).
edge(d, a, 40).
stay(a, 10).
stay(c, 30).
stay(b, 15).
stay(d, 20).
route(Start, End, Route, Cost) :-
edge(Start, End, Cost),
append([Start], [End], Route).
route(Start, End, Route, Cost) :-
edge(Start, Next, FirstCost),
stay(Next, StayTime),
route(Next, End, NewRoute, SecondCost),
Cost is FirstCost + SecondCost + StayTime,
append([Start], NewRoute, Route).
swipl で次の出力が得られます。
?- route(a,b,Routing,Cost).
Routing = [a, b],
Cost = 10 ;
Routing = [a, c, b],
Cost = 90 ;
Routing = [a, c, d, b],
Cost = 150 ;
Routing = [a, c, d, a, b],
Cost = 180 ;
Routing = [a, c, d, a, c, b],
Cost = 260 .
ご覧のとおり、3 番目のルートの後、サイクルが発生し始めます。それらを避けたいのですが、どうすればいいのか少しわかりません。