【问题标题】:Prolog: Finding path in a mazeProlog:在迷宫中寻找路径
【发布时间】:2014-11-21 19:21:30
【问题描述】:

假设我们有一个机器人,它在棋盘上,可以像国王一样移动。

棋盘的坐标从 [1,1] 到 [8,8]。

起始位置是 [1,1] 最终位置是 [8,8]。有一个列表 X 包含障碍物坐标列表,例如 [[1,4],[2,5],[5,6]]。问题是:有没有可能的方式让机器人从起点移动到终点。

我做了这个谓词:

path([A,B],_):- A is 8, B is 8.
path([A,B],X):- 
        possibleMoves(A,B,L), % possibleMoves returns a list of all the possible coords that
        the robot can go to. (Example for [1,1] are [[0,1],[0,0],[2,1]...])

        member([Ex,Ey],L), % member generates all the possible members from the list L
        not(member([Ex,Ey],X)), % if this member is not member of the "forbidden ones"
        Ex<9,Ex>0,Ey<9,Ey>0, % and its coords are on the board
        path([Ex,Ey],X).


isTherePath(X):- possibleMoves(1,1,L),
                 member(E,L),
                 path(E,X).

但是有一个错误,它没有返回任何值。递归永远不会停止我找不到原因。

【问题讨论】:

  • 第一行的意图是什么?它总是将 8 分配给 A 和 B。我猜你想比较而不是分配。

标签: recursion prolog maze transitive-closure


【解决方案1】:

在一个谓词中定义什么是有效步骤 - 包括您拥有的所有限制。坚持这个命名约定:X0“第一个”值,X“最后一个”值

step(Forbidden,[X0,Y0],[X,Y]) :-
   possibleMoves(X0,Y0,L), % rather: possibleMove([X0,Y0],L),
   member([X,Y],L),
   between(1,8,X),
   between(1,8,Y),
   non_member([X,Y],Forbidden).

现在你有一条路径:

 ..., closure0(step(Forbidden), S0,S), ...

closure0/3 负责循环。

【讨论】:

  • 谢谢,但我不能使用闭包,我必须自己做谓词。我不能做一个谓词step 来检查我现在的坐标是否是最终坐标。如果我不是,我会使用你定义的这一步。
猜你喜欢
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多