好的,我有一个 BFS 的 Lisp 实现,我正在尝试将其转换为爬山搜索。
这是我的 BFS 代码的样子:
; 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 中那样总是扩展左节点。
我使用的图表如下所示:
(a (b 3) (c 1))
(b (a 3) (d 1))
我有一个转换函数可以使它与上述 BFS 实现一起工作,但现在我需要使用这种图形格式将其转换为爬山。
我只是不确定从哪里开始,并且一直在尝试无济于事。我知道我主要需要更改expand-queue
函数以扩展最近的节点,但我似乎无法制作一个函数来确定哪个节点最近。
谢谢您的帮助!