Is it correct this interpretation of DFS algorithm version that avoids loops in Prolog? -


i studying dfs algorithm dfs algorithm version avoids loops, code

/* true solution path start node node goal state node    if true depthfirst2/3 predicate where:    []: of nodes visited (at beginning empty)    node: current node visiting    solution: path (without cycles) start node current node node  */ solve2(node, solution) :- depthfirst2([], node, solution).  /* base case: [node|path] solution path fro start node goal node if               true path list of visited node until reach node , node               goal state */ depthfirst2(path, node, [node|path]) :- goal(node).   /* rule: else (if node not goal state) , path list of visited node ,          sol path start node current node node true if          true that:          node1 successor of node          have not visited node1 (node1 not in visited node list)          add node list of visited node , execute depthfirst2 searching path          node1 */ depthfirst2(path, node, sol) :- s(node, node1),                                          not(member(node1, path)),                                    depthfirst2([node|path], node1, sol).    

is interpretation correct?

tnx

your reading seems ok, except path reversed. using 3 arguments predicate meant reverse path on goal reaching.

to enforce else part, think need cut after goal(node) succeeds. otherwise, extending path - possibly - after target node. if unique, there little utility in doing, because ruled out subsequent \+ member test.

for efficiency, call \+ memberchk instead of \+ member, memberchk doesn't leave choicepoints , (in swi-prolog) implemented efficiently @ lower level member.

with base data:

s(a, b). s(b, c). s(c, d). s(a, d). goal(d). 

you can see difference of cut after goal(node):

without

?- solve2(a, p). p = [d, c, b, a] ; p = [d, a] ; false. 

with cut

?- solve2(a, p). p = [d, c, b, a] ; p = [d, a]. 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -