Question

I want to do a graph search with JIProlog. The below example works fine without the memberchk, but then it returns paths with cycles, which I don't want. When I do include it, however, Prolog freezes, probably because of the infinite search.

connected(ac,a,b). connected(ac,a,c). connected(ac,b,c). 
connected(ac,b,a). connected(ac,c,a). connected(ac,c,b).

path(A,B,[AB]) :- connected(AB,A,B).
path(A,C,[H|T]) :- connected(H,A,B), path(B,C,T), \+ memberchk(H,T).

In this answer I found why (the list of edges is not yet instantiated) and a hint to a solution (using freeze/2). However, freeze/2 doesn't work in JIProlog, which is what I'm using. Can anyone help me to an alternative solution?

Edit: I know for graphs in general it would be a solution to keep track of nodes instead, such as in this example, but for my particular application the "nodes" can also be on an edge, which is why I want to check for edges that were visited rather than nodes that were visited.

Was it helpful?

Solution

I'm not sure to understand your requirement. I would try to adapt the suggested answer.

% get a path from start to end
path(Start, End, Path) :-
    path(Start, End, [], Path).

path(A, B, Visited, [AB|Visited]) :- connected(AB, A, B).

path(A, C, Visited, Path) :-
    connected(AB, A, B),
    \+ memberchk(AB, Visited),
    path(B, C, [AB|Visited], Path).

beware: untested code....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top