prolog list out every possible path of the recursi

2019-08-27 20:56发布

I would like to list out every possible path

country(england,france). 
country(france,bulgaria).
country(bulgaria,germany).
country(england,bulgaria).
country(germany,italy).
edit: additional to

country(germany,italy).
country(england,italy).
country(england,greece).
country(greece,france).

connectto(X, Y) :-
country(X, Y).

?-op(150,xfy,to).

X to Y:-get_waypoints(X,Y,Waypoints),write(Waypoints),fail.

get_waypoints(Start, End, [Waypoint|Result]) :-
   country(Start, End),
   !;country(Start, Waypoint),
   get_waypoints(Waypoint, End, Result).

otherwise from the original code the system will give out

   | ?- england to italy.
   []no

from the code you mention.

now the problem comes into

    | ?- england to italy.
    [_31242|_31243][france,bulgaria,germany,_31332|_31333]   
    [bulgaria,germany,_31422|_31423]
    [greece,france,bulgaria,germany,_31602|_31603]no

although it shows out all possible route.

Any solution will be appreciated.

1条回答
The star\"
2楼-- · 2019-08-27 21:42

Ask if you need explanation :

country(bulgaria,germany).
country(england,bulgaria).
country(england,france). 
country(england,greece).
country(england,italy).
country(france,bulgaria).
country(greece,france).
country(germany,italy).

:- op(150, xfy, to).

X to Y :-
    findall(Waypoint, get_waypoints(X,Y,Waypoint), Waypoints),
    write(Waypoints).

get_waypoints(Start, End, []) :- 
    country(Start, End).
get_waypoints(Start, End, [Waypoint|Result]) :-
    country(Start, Waypoint),
    get_waypoints(Waypoint, End, Result).

Use is :

?- england to italy.

Here, I updated my code to match your expectations.

查看更多
登录 后发表回答