route(X, Y, [X, Y]) :- link(X,Y).
route(X, Y, [X | TY]) :-
link(X, T),
route(T, Y, TY).
With route
as above, the following code searches for the path in increasing order of length.
?- length(X, _), route(entry,exit, X).
X = [entry, a, b, e, f, exit] ;
X = [entry, a, b, c, d, e, f, exit] ;
X = [entry, a, b, e, f, c, d, e, f, exit] ;
X = [entry, a, b, c, d, e, f, c, d, e, f, exit] ;
X = [entry, a, b, e, f, c, d, e, f, c, d, e, f, exit]
Since we did not constrain route
predicate to disallow repeated nodes, we have loops at higher lengths of the path.
EDIT:
The following works SWI-Prolog check if your system has dif/2
. Using maplist
here allows us to do increasing path length search.
route(X, Y, [X, Y]) :- link(X,Y).
route(X, Y, [X|TY]) :-
link(X, T),
maplist(dif(X), TY), % X is different from all nodes in TY
route(T, Y, TY).
If you do not have dif
use + member(X, TY)
after the route(T, Y, TY)
.
This gives
?- route(entry, exit, X).
X = [entry, a, b, e, f, exit] ;
X = [entry, a, b, c, d, e, f, exit] ;
After the couple of solutions it will loop endlessly. If you want that to stop that happening you can constrain the length of path to number of existing nodes
?- between(2, 8, N), length(X, N), route(entry, exit, X).
N = 6,
X = [entry, a, b, e, f, exit] ;
N = 8,
X = [entry, a, b, c, d, e, f, exit] ;
false.