'Finding shortest path of undirected weighted graph in prolog
I am trying to do a shortest path for a London underground system inside prolog, and I'm stuck I've managed to get the code to return lists of all the possible routes however I need it to print the shortest weighted route an example of the desired outcome would be: [aaa,bbb,ccc,ddd,eee,40] where aaa,bbb etc. are stations in the knowledge base Here is my code
edge(chrc,embk,3).
edge(embk,wtrl,6).
edge(kksp,angl,16).
edge(angl,olds,20).
edge(olds,mrgt,9).
edge(mrgt,monm,9).
edge(monm,lnbg,6).
edge(lnbg,borg,9).
edge(wtrl,bank,33).
%go(leic,wtrl,R,D).
connected(X,Y,L) :-
edge(X,Y,L).
connected(X,Y,L) :-
edge(Y,X,L).
connected(X,Y,L) :- connected(X,Z,L),connected(Z,Y,L).
connected(Y,X,L) :- connected(Y,Z,L),connected(Z,X,L).
path3(Routes, Destination, Route):-
shortest(Routes, Shortest, RestRoutes),
proceed(Shortest, Destination, RestRoutes, Route).
proceed(r(Distance, Route), Destination, _, Route):-
Route = [Destination|_].
proceed(r(Distance, [Last|Trail]), Destination, Routes, Route):-
findall(r(D1, [Z,Last|Trail]),
legalnode(Last, Trail, Z, Distance, D1), List),
append(List, Routes, NewRoutes),
path3(NewRoutes, Destination, Route).
shortest([Route|Routes], Shortest, [Route|Rest]) :-
shortest(Routes, Shortest, Rest),
shorter(Shortest, Route),
!.
shortest([Route|Rest], Route, Rest).
shorter(r(M1,_), r(M2,_)) :- M1 < M2.
legal(X, []).
legal(X, [H|T]) :- not(X = H), legal(X,T).
legalnode(X, Trail, Y, Distance, NewDistance) :-
(edge(X,Y, Cost); edge(Y,X, Cost)),
legal(Y, Trail),
NewDistance is Distance + Cost.
go(Start, Destination, Route) :-
path3([r(0, [Start])], Destination, R),
reverse(R, Route).
There are more edges defined but it takes too much space
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|