首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Lisp -爬山

Lisp -爬山
EN

Stack Overflow用户
提问于 2011-04-29 22:36:22
回答 1查看 1.5K关注 0票数 3

好的,我有一个BFS的Lisp实现,我正试图将其转换为爬山搜索。

下面是我的BFS代码:

代码语言:javascript
复制
; The list of lists is the queue that we pass BFS.  the first entry and 
; every other entry in the queue is a list.  BFS uses each of these lists and 
; the path to search.  

(defun shortest-path (start end net)   
  (BFS end (list (list start)) net))

;We pass BFS the end node, a queue containing the starting node and the graph 
;being searched(net)   

(defun BFS (end queue net)
  (if (null queue) ;if the queue is empty BFS has not found a path so exit
      nil
      (expand-queue end (car queue) (cdr queue) net)))

(defun expand-queue (end path queue net)
  (let ((node (car path)))
    (if (eql node end)   ; If the current node is the goal node then flip the path
                         ; and return that as the answer
        (reverse path)
        ; otherwise preform a new BFS search by appending the rest of 
        ; the current queue to the result of the new-paths function
        (BFS end (append queue (new-paths path node net)) net))))

; mapcar is called once for each member of the list new-paths is passed
; the results of this are collected into a list
(defun new-paths (path node net)
  (mapcar #'(lambda (n) (cons n path))
         (cdr (assoc node net))))

现在,我知道不是像在BFS中那样总是展开左侧节点,而是需要展开看起来最接近目标状态的节点。

我使用的图形如下所示:

代码语言:javascript
复制
(a (b 3) (c 1))  
(b (a 3) (d 1))

我有一个转换函数来使上面的BFS实现工作,但现在我需要使用此图形格式将其转换为爬山。

我只是不确定从哪里开始,并且一直在尝试,但都无济于事。我知道我主要需要更改expand-queue函数来展开最近的节点,但我似乎不能创建一个函数来确定哪个节点是最近的。

谢谢你的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-04-30 18:38:51

将内容追加到列表的末尾是错误的。这是使用列表执行的代价最高的操作。复制整个列表,然后追加另一个列表。您可以在递归过程中使用它,这意味着每次展开节点以创建新路径时都会执行此操作。

如果您将项放入队列,则需要查看执行此操作的顺序。在广度优先的情况下,在移动到下一个级别之前,访问一个级别中的每个节点。爬山需要你使用加权函数对“最好”的候选者进行排序。因此,您需要某种类型的函数来计算当前节点和下一个候选节点的数值。然后,您需要对候选对象进行排序,并首先展开“最佳”节点。对于LIFO (后进先出)队列,这意味着最有希望的节点需要被推到最后,因此它将是第一个被扩展的节点。请注意,后进先出队列非常适合单链表。FIFO (先进先出)不是这样的。

计算机科学的一个典型概念是数据抽象。如果LIFO队列是这样的数据结构,则需要定义诸如MAKE-LIFO-QUEUE、EMPTY- QUEUE -P等函数。然后,您将使用这些函数而不是LIST、NULL和其他函数,它们使数据结构的目的更加清晰。这会使您的代码变得更长,但是由于Lisp列表是通用的,并且可以(ab-)用于所有类型的使用场景,因此仅看列表操作并不能清楚地说明它们的意图。对于更复杂的图形算法,这一点尤为重要。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5833471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档