【问题标题】:Prevent cycle in Depth first search using prolog使用序言防止深度优先搜索循环
【发布时间】:2022-07-27 20:44:46
【问题描述】:

有什么办法可以防止这段代码出现循环。

move(a,b).
move(b,a).
move(a,c).
move(b,d).
move(b,e).
move(d,h).
move(d,i).
move(e,j).
move(e,k).
move(c,f).
move(c,g).
move(f,l).
move(f,m).
move(g,n).
move(g,o).
goal(n).


goSolveTheMaze(Start,Way) :-
    dfs(Start, Way),!.

dfs(Goal, [Goal]) :-
   goal(Goal),!.

dfs(Start, [Start|Way])  :-
    move(Start, N),
    dfs(N, Way).

所以当move(a,b) 移动到(b,c) 时不要回到(b,a), 当运行goSolveTheMaze(a,path)。 输出应该是path=[a,c,g,n]

【问题讨论】:

标签: prolog artificial-intelligence depth-first-search


【解决方案1】:

如果您将第三个参数添加到dfs,它是您已经访问过的地方的列表,该怎么办?然后您可以使用\+/1member/2 来避免返回您已经去过的地方。

例如,如果您使用以下内容:

move(a,b).
move(b,a).
move(a,c).
move(b,d).
move(b,e).
move(d,h).
move(d,i).
move(e,j).
move(e,k).
move(c,f).
move(c,g).
move(f,l).
move(f,m).
move(g,n).
move(g,o).
goal(n).


goSolveTheMaze(Start,Way) :-
    dfs(Start, Way, [Start]),!.

dfs(Goal, [Goal], _) :-
   goal(Goal),!.

dfs(Start, [Start|Way], Visited)  :-
    move(Start, N),
    \+ member(N, Visited),
    dfs(N, Way, [N|Visited]).

然后查询:

?- goSolveTheMaze(a, X).

会产生结果:

X = [a, c, g, n]

更新以回应评论“你能告诉我 \+ 做什么吗?”:

\+ 谓词在其论点无法被证明时为真。因此,在上面的示例中,\+ member(N, Visited) 行的意思是“当 N 不是访问列表的成员时”。

见:https://www.swi-prolog.org/pldoc/man?predicate=%5C%2B/1

【讨论】:

  • 你能告诉我 \+ 是做什么的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多