 <p>Try something like</p> <pre><code>connect(Bgn,End,Path) :- % to find a path between two nodes in the graph connected(Bgn,End,[],P) , % - we invoke the helper, seeding the visited list as the empty list reverse(P,Path) % - on success, since the path built has stack semantics, we need to reverse it, unifying it with the result . connected(X,Y,V,[X,Y|V]) :- % can we get directly from X to Y? path(X,_,Y) % - if so, we succeed, marking X and Y as visited . % connected(X,Y,V,P) :- % otherwise... path(X,_,T) , % - if a path exists from X to another room (T) T \= Y , % - such that T is not Y \+ member(X,V) , % - and we have not yet visited X connected(T,Y,[X|V],P) % - we continue on, marking X as visited. . </code></pre> <p>You'll note the test for having visited the room before. If your graph has cycles, if you don't have some sort of test for having previously visited the node, you'll wind up going around and around in circles...until you get a stack overflow.</p>