transitive closure - getting out of local stack at prolog -


p(0,0). p(0,1). p(0,2). p(0,3). p(0,4). p(1,1). p(1,2). p(1,3). p(1,4). p(1,0). p(2,0). p(2,1). p(2,2). p(2,3). p(2,4). p(3,0). p(3,1). p(3,2). p(3,3). p(3,4). p(4,0). p(4,1). p(4,2). p(4,3). p(4,4).  adjacent(p(x,y),p(x,z)) :-     p(x,y),     p(x,z),     z y+1. adjacent(p(x,y),p(x,z)) :-     p(x,y),     p(x,z),     z y-1. adjacent(p(x,y),p(z,y)) :-     p(x,y),     p(x,z),     z x+1. adjacent(p(x,y),p(z,y)) :-     p(x,y),     p(x,z),     z x-1.  adjacentc(x,y) :-     adjacent(x,y). adjacentc(x,y) :-     adjacent(x,z),     adjacentc(z,y). 

i don't know why code wrote isn't working.

e.g.:

?- adjacentc((0,0),(4,4)). error 

quick answer: following works , terminates using closure/3 defined elsewhere.

adjacentd(x,y) :-    closure(adjacent,x,y). 

however, approach extremely slow, due inefficient definition of adjacent/3. here better 1 / oh forget it, here more correct one, first:

adjacent2(p(x0,y0),p(x,y)) :-    p(x0,y0),    (  x0 = x,       p(x,y),       abs(y0-y) =:= 1    ;  y0 = y,       p(x,y),       abs(x0-x) =:= 1    ). 

Comments