DFS算法版本的这种解释是否正确避免了Prolog中的循环?

时间:2013-05-10 07:44:42

标签: prolog

我正在研究DFS算法的避免循环的DFS算法版本,这就是代码

/* It is TRUE that Solution is the path from the start node Node to a goal state node
   if it is TRUE the depthfirst2/3 predicate where:
   []: it is the of nodes that was already visited (at the beginning is empty)
   Node: is the current node that I am visiting
   Solution: is the path (without cycles) from the start node to the current node Node 
*/
solve2(Node, Solution) :- depthfirst2([], Node, Solution).

/* BASE CASE: [Node|Path] is the Solution path fro the start node to a GOAL node if it
              is TRUE that Path is the list of visited node until reach Node and Node
              is a GOAL state
*/
depthfirst2(Path, Node, [Node|Path]) :- goal(Node).


/* RULE: Else (if Node this is not a GOAL state) and Path is the list of visited node and
         Sol is the path from the start node to the current node Node it is TRUE if it is
         True that:
         Node1 is the successor of Node
         I have not already visited Node1 (Node1 is not in the visited node list)
         Add Node to the list of visited node and execute depthfirst2 searching the path
         to Node1
*/
depthfirst2(Path, Node, Sol) :- s(Node, Node1),             
                            not(member(Node1, Path)),       
                            depthfirst2([Node|Path], Node1, Sol).   

我的解释是否正确?

TNX

1 个答案:

答案 0 :(得分:2)

你的阅读似乎没问题,除了路径颠倒了。使用3参数谓词通常意味着反转目标到达的路径。

为了强制执行Else部分,我认为在goal(Node)成功后你需要削减。否则,您正在扩展路径 - 可能 - 在目标Node之后。如果这是唯一的,那么实际上没什么用处,因为它将被随后的\+ member测试排除。

为了提高效率,请致电\+ memberchk而不是\+ member,因为memberchk不会留下选择点,并且(在SWI-Prolog中)在低于member的水平上有效实施

使用此基础数据:

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

您可以在goal(Node)之后看到切割的差异:

?- 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].