深度优先搜索算法Prolog

时间:2014-11-21 16:17:16

标签: algorithm prolog depth-first-search transitive-closure

我希望你能帮助我。

我正在尝试了解Prolog中的Depth First搜索算法,我遇到了以下代码

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.

我有点理解发生了什么事,但我不能发现或发明一些我可以用它的事实。

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

提前谢谢

2 个答案:

答案 0 :(得分:1)

以下是prolog代码中使用的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 prolog并将其粘贴到终端。

然后查询右侧的代码和类型:solve(a,Sol)

解决方案是:Sol = [j,e,b,a]

您可以通过输入以下内容来调试此代码:trace,(solve(a,Sol))。

以下是prolog代码中使用的BFS的示例

使用与之前相同的步骤进行嗖嗖声并查询

解决方案是: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

答案 1 :(得分:0)

您只需要在图表中制作描述有效移动的事实。

因此,例如,如果您有节点A,B,C和D,则图形上的每个边都有一个mov()事实。如果A有B和C的边,而B有D的边,你的事实将是

mov(A, B).
mov(A, C).
mov(B, D).

基本上,绘制图形并为从节点到另一个节点的每条路径写上面的事实。