我有一个BFS的实现,我在其他地方得到并略微修改了一下,但我在它的输入上遇到了问题。
它获取一个图,并将其视为'((a B c) (b c) (c d)),但我给它的输入是一个加权图...我知道它对BFS没有用处,但稍后我会使用更远的权重。这个输入看起来像
'(
(a (b 3) (c 1))
(b (a 3) (d 1))
(c (a 1) (d2) (e 2))
)
诸若此类。
我的代码:
(defun shortest-path (start end net)
(BFS end (list (list start)) net))
(defun BFS (end queue net)
(if (null queue)
nil
(expand-queue end (car queue) (cdr queue) net)))
(defun expand-queue (end path queue net)
(let ((node (car path)))
(if (eql node end)
(reverse path)
(BFS end
(append queue
(new-paths path node net))
net))))
(defun new-paths (path node net)
(mapcar #'(lambda (n)
(cons n path))
(cdr (assoc node net))))我只是不确定我需要在哪里修改它来接受新的样式列表,或者创建一个帮助函数来正确地格式化它?
发布于 2011-04-11 17:57:51
您需要指定表示图形的列表的含义。目前您只给出了一个示例列表。
当图形具有如下语法时:
graph = (node*)
node = (name nextnodename*)
name = SYMBOL
nextnodename = SYMBOL那么转换函数可能是:
(defun convert-graph (graph)
(mapcar (lambda (node)
(destructuring-bind (name . nodes) node
(cons name (mapcar #'first nodes))))
graph))或者,如果您可能需要其他提取功能:
(defun convert-graph (graph &key (key #'first))
(mapcar (lambda (node)
(destructuring-bind (name . nodes) node
(cons name (mapcar key nodes))))
graph))示例:
(convert-graph '((a (b 3) (c 1))
(b (a 3) (d 1))
(c (a 1) (d 2) (e 2)))
:key #'first)
((A B C) (B A D) (C A D E))现在,您可能需要删除重复的链接。但这取决于图形描述的语法和语义。
https://stackoverflow.com/questions/5614568
复制相似问题