Prolog routing between 2 points and making a list

2019-08-07 17:11发布

问题:

I need a method that returns all the roads* used in a route between two points, here's the map I have:

Example, to point A to E, i need a list of roads used, like that:

route(a, e, R).
R = [1,5].

I'm having problems in marking the routes that i've already visited, and on top of that, register the number of the road used in a list.

So here's my code so far:

road(1,a,b).
road(2,a,d).
road(3,b,c).
road(4,c,d).
road(5,b,e).
road(6,c,f).
road(7,d,f).
road(8,e,f).

connected(A,B) :- road(_,A,B).

route(A, B, R) :- road(R, A, B), road(R, B, A).
route(A, B, [R2|R]) :- route(A, C, R2), route(C, B, R2).

回答1:

Thanks for the help! I did know the procedure, but i was finding difficult in appending the roads to the list, here's the final code:

road(1,a,b).
road(2,a,d).
road(3,b,c).
road(4,c,d).
road(5,b,e).
road(6,c,f).
road(7,d,f).
road(8,e,f).

route(X,Y,[R]) :- road(R,X,Y).
route(X,Y,[R1|R2]) :- road(R1,X,Z), route(Z,Y, R2).

Here's my desired output:

?- route(a,f,R).
R = [1, 3, 6] .

I was making a confusion in appending the list in the second definition of route, the examples helped me. Thanks for the help!!



回答2:

Your solution is still not resisting cycles in graph, here is once that keeps it in mind

route(A,A,R,R).
route(A,B,R,R2) :- road(Rx,A,C), \+ member(Rx,R) , route(C,B,[Rx|R],R2).
route(A,B,R) :- route(A,B,[],Rx), reverse(R,Rx).