Prolog中带最大深度约束的迭代深化
我必须修改以下Prolog程序,该程序在图形上实现迭代深化dfs搜索:Prolog中带最大深度约束的迭代深化,prolog,shortest-path,Prolog,Shortest Path,我必须修改以下Prolog程序,该程序在图形上实现迭代深化dfs搜索: s(a, b). s(b, c). s(c, d). s(a, d). goal(d). /* Solution is the inverse list of the visited node from the start node Node and a goal node if it is TRUE that: path/3 predicate is TRUE (S
s(a, b).
s(b, c).
s(c, d).
s(a, d).
goal(d).
/* Solution is the inverse list of the visited node
from the start node Node and a goal node
if it is TRUE that:
path/3 predicate is TRUE (Solution is the inverse list
from the start node Node and a GoalNode)
and it is TRUE that GoalNode is a goal
*/
depth_first_iterative_deepening(Node, Solution) :-
path(Node, GoalNode, Solution),
goal(GoalNode).
/* Path/3 predicate generate, for the given initial node,
all the possibles acyclic paths of increasing
length
*/
/* BASE CASE: The shorter path from a node X to itself is Path=[X] */
path(Node, Node, [Node]).
/* GENERAL CASE: If I have to go from a start node X
to an end node Y and X != Y
[LastNode|Path] is the path from FirstNode and LastNode
if it is TRUE that:
1) Path is the path from FirstNode and OneButLast node
2) Exist an edge from OneButLast and LastNode
3) I have yet never visited LastNode
*/
path(FirstNode, LastNode, [LastNode|Path]) :-
path(FirstNode, OneButLast, Path),
s(OneButLast, LastNode),
not(member(LastNode, Path)).
路径/3
谓词为给定的初始节点生成所有可能的、长度递增的非循环路径,因此使用深度优先\u迭代\u深化/2
谓词I按长度顺序生成从开始节点到结束节点的所有解(从最短的到最长的)
好的,所以我必须修改这个程序,以限制解决方案的长度
我必须有一个深度\u优先\u迭代\u深化2/3
谓词,如下所示:
depth_first_iterative_deepening2(Node, Max, Solution)
其中,Max
是访问节点的最大数量,因此解决方案
是可接受的
因此,如果Solution
长度小于或等于Max
值,则Solution
是从开始节点node
到目标节点的解决方案路径
我曾尝试在前面的谓词中进行此更改,但它存在一些问题,无法正常工作:
depth_first_iterative_deepening2(Node, Max, Solution) :-
path2(Node, GoalNode, Solution),
goal(GoalNode),
length(Solution, Length),
write(Length),
(Length =< Max).
从跟踪来看,问题似乎在于当(Length=
失败时,它会再次调用路径2/3
谓词以找到另一个解决方案(这是相同的,因为path2/3
总是找到第一次调用的最短路径,因此它将找到导致失败的相同解决方案)
我希望如果(Length=
检查失败,那么深度\u优先\u迭代\u深化2/3
必须失败
我可以用切割来做这件事吗?如果可以,怎么做?这和我不久前提出的“技巧”是一样的 在调用访问之前进行测试:
depth_first_iterative_deepening2(Node, Max, Solution) :-
length(Solution, Length),
Length =< Max,
path2(Node, GoalNode, Solution),
goal(GoalNode).
depth\u first\u iterative\u deptening2(节点、最大值、解决方案):-
长度(溶液,长度),
长度=
这就是我不久前提出的“把戏”
在调用访问之前进行测试:
depth_first_iterative_deepening2(Node, Max, Solution) :-
length(Solution, Length),
Length =< Max,
path2(Node, GoalNode, Solution),
goal(GoalNode).
depth\u first\u iterative\u deptening2(节点、最大值、解决方案):-
长度(溶液,长度),
长度=
您可以试试
( (Length =< Max) ; (Length > Max), !, fail).
((长度=Max),!,失败)。
而不是
(Length =< Max).
(长度=
您可以试试
( (Length =< Max) ; (Length > Max), !, fail).
((长度=Max),!,失败)。
而不是
(Length =< Max).
(长度=
我在这里提问之前尝试过,但仍然不起作用:光标闪烁且未得出错误的结论我在这里提问之前尝试过,但仍然不起作用:光标闪烁且未得出错误的结论。它起作用了……现在很清楚:无论是否找到有效的解决方案,最后都会失败并退出程序m!!!@AndreaNobili是的;当长度=