gpt4 book ai didi

algorithm - 深度优先搜索算法序言

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:17:45 24 4
gpt4 key购买 nike

我希望你能帮我解决这个问题。

我正在尝试了解 Prolog 中的深度优先搜索算法,我遇到了以下代码

go(Start, Goal) :-
empty_stack(Empty_been_list),
stack(Start, Empty_been_list, Been_list),
path(Start, Goal, Been_list).

% path implements a depth first search in PROLOG

% Current state = goal, print out been list
path(Goal, Goal, Been_list) :-
reverse_print_stack(Been_list).

path(State, Goal, Been_list) :-
mov(State, Next),
% not(unsafe(Next)),
not(member_stack(Next, Been_list)),
stack(Next, Been_list, New_been_list),
path(Next, Goal, New_been_list), !.

reverse_print_stack(S) :-
empty_stack(S).
reverse_print_stack(S) :-
stack(E, Rest, S),
reverse_print_stack(Rest),
write(E), nl.

我有点理解正在发生的事情,但我终其一生都无法找到或发明一些我可以用它来使用的事实。

请帮忙。即使它是一组非常简单的事实,我也只需要从某个地方开始

提前致谢

最佳答案

以下是序言代码中使用的DFS示例

% solve( Node, Solution):
% Solution is an acyclic path (in reverse order) between Node and a goal

solve( Node, Solution) :-
depthfirst( [], Node, Solution).

% depthfirst( Path, Node, Solution):
% extending the path [Node | Path] to a goal gives Solution

depthfirst( Path, Node, [Node | Path] ) :-
goal( Node).

depthfirst( Path, Node, Sol) :-
s( Node, Node1),
\+ member( Node1, Path), % Prevent a cycle
depthfirst( [Node | Path], Node1, Sol).

depthfirst2( Node, [Node], _) :-
goal( Node).

depthfirst2( Node, [Node | Sol], Maxdepth) :-
Maxdepth > 0,
s( Node, Node1),
Max1 is Maxdepth - 1,
depthfirst2( Node1, Sol, Max1).


goal(f).
goal(j).
s(a,b).
s(a,c).
s(b,d).
s(b,e).
s(c,f).
s(c,g).
s(d,h).
s(e,i).
s(e,j).

为了测试此代码,请转到 Swish SWI 序言并将其粘贴到终端中。

然后查询代码并在右侧输入:solve(a, Sol)

解为:Sol = [j, e, b, a]

您可以通过键入以下命令调试此代码:trace, (solve(a, Sol))。

以下是在序言代码中使用 BFS 的示例

继续使用与之前相同的步骤进行 swish 和查询

解为:Sol = [f, c, a]

% solve( Start, Solution):
% Solution is a path (in reverse order) from Start to a goal

solve( Start, Solution) :-
breadthfirst( [ [Start] ], Solution).

% breadthfirst( [ Path1, Path2, ...], Solution):
% Solution is an extension to a goal of one of paths

breadthfirst( [ [Node | Path] | _], [Node | Path]) :-
goal( Node).

breadthfirst( [Path | Paths], Solution) :-
extend( Path, NewPaths),
append( Paths, NewPaths, Paths1),
breadthfirst( Paths1, Solution).

extend( [Node | Path], NewPaths) :-
bagof( [NewNode, Node | Path],
( s( Node, NewNode), \+ member( NewNode, [Node | Path] ) ),
NewPaths),
!.

extend( Path, [] ). % bagof failed: Node has no successor
s(a,b).
s(a,c).
s(b,d).
s(b,e).
s(c,f).
s(c,g).
s(d,h).
s(e,i).
s(e,j).
goal(j).
goal(f).

希望这有助于理解 DFS 和 BFS

使用这张图来帮助你理解这棵树

enter image description here

关于algorithm - 深度优先搜索算法序言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27065774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com