将Depth First Search转换为prolog中的Best-First(贪婪)搜索

时间:2014-11-21 23:46:16

标签: prolog depth-first-search greedy

我想将我的深度优先搜索修改为最佳搜索。

我的深度优先搜索如下

goal(fivet).

move(onea,twoa).
move(onea,twob).
move(onea,twoc).
move(onea,twod).
move(twoa,threea).
move(twoa,threeb).
move(twoa,threec).
move(threea,foura).
move(threea,fourb).
move(foura,fivea).
move(fourb,fiveb).
move(threeb,fourc).
move(threeb,fourd).
move(fourc,fivec).
move(fourd,fived).
move(threec,foure).
move(threec,fourf).
move(foure,fivee).
move(fourf,fivef).
move(twob,threed).
move(twob,threee).
move(twob,threef).
move(threed,fourg).
move(threed,fourh).
move(fourg,fiveg).
move(fourh,fiveg).
move(threee,fouri).
move(threee,fourj).
move(fouri,fivei).
move(fourj,fivej).
move(threef,fourk).
move(threef,fourl).
move(fourk,fivek).
move(fourl,fivel).
move(twoc,threeg).
move(twoc,threeh).
move(twoc,threei).
move(threeg,fourm).
move(threeg,fourn).
move(fourm,fivem).
move(fourn,fiven).
move(threeh,fouro).
move(threeh,fourp).
move(fouro,fiveo).
move(fourp,fivep).
move(threei,fourq).
move(threei,fourr).
move(fourq,fiveq).
move(fourr,fiver).
move(twod,threej).
move(twod,threek).
move(twod,threel).
move(threej,fours).
move(threej,fourt).
move(fours,fives).
move(fourt,fivet).
move(threek,fouru).
move(threek,fourv).
move(fouru,fiveu).
move(fourv,fivev).
move(threel,fourw).
move(threel,fourx).
move(fourw,fivew).
move(fourx,fivex).


dfs(A, Path, Path) :- goal(A).

dfs(A, Checked, Path) :-
    % try a move
    move(A, A2),
    % ensure the resulting state is new
    \+member(A2, Checked),
    % and that this state leads to the goal
    dfs(A2, [A2|Checked], Path).

% query = dfs(onea, [], Path).

请原谅漫长的节目,这是一个相当大的搜索树。

Best-First search tree

我已经为所有节点提供了一个度量X.

将上述程序从深度优先改为最佳优先级是一个简单的过程吗?

任何帮助都会非常感激。

谢谢

2 个答案:

答案 0 :(得分:1)

诀窍是不允许prolog为您选择下一个move,而是收集所有可能的move,以便您可以使用您的条件来选择最佳标准。

查看find_all谓词。

答案 1 :(得分:1)

使用假指标(请参阅isub)和目标

goal(fivex).

dfs(A, Path, Path) :- goal(A).
dfs(A, Checked, Path) :-
    % get all possible moves, ordered
    setof(W-A2, (
      move(A, A2),
      % avoid looping - but in displayed graph there should not be
      \+memberchk(A2, Checked),
      % fake metrics value, maybe should be reversed
      isub(A, A2, true, W)
    ), L),
    % peek next step in increasing metric
    member(_-A2, L), % 
    % leads to the goal
    dfs(A2, [A2|Checked], Path).

如果您知道没有循环,您可以通过这种方式简化,从开始到目标订购路径

dfs(A, [A]) :- goal(A).
dfs(A, [A|Path]) :-
    % try a move
    setof(W-A2, (
        move(A, A2),
        isub(A, A2, true, W) % fake metrics, maybe reverse
    ), L),
    % peek next step in increasing metric
    member(_-A2, L), % 
    % and that this state leads to the goal
    dfs(A2, Path).