LISP - 广度优先搜索
我有一个从其他地方获得的 BFS 实现并稍加修改,但我的输入遇到了问题。
它需要一个图表,并将其视为 '((abc) (bc) (cd)) 但我给它的输入是一个加权图...我知道它对 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))))
我只是不确定我最有可能需要在哪里修改它以接受新的样式列表,或者创建一个帮助函数来正确格式化它?
I have an implementation of BFS I got elsewhere and modified slightly, but I am having problems with its input.
It takes a graph, and will take it as '((a b c) (b c) (c d))
But my input I am giving it is a weighted graph... I know it's not useful for the BFS, but I use the weights farther down the line later. This input looks like'(
(a (b 3) (c 1))
(b (a 3) (d 1))
(c (a 1) (d2) (e 2))
)
And so on.
My code:
(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))))
I'm just not sure where I need to most likely modify it to accept the new style list, or make a help function to format it correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要指定代表您的图表的列表的含义。目前您只给出了一个示例列表。
当图形具有如下语法时:
那么转换函数可能是:
或者如果您可能需要其他提取函数:
示例:
现在您可能需要删除重复的链接。但这取决于图描述的语法和语义。
You need to specify what the list that represents your graph means. Currently you have only given an example list.
When the graph has a syntax like:
Then a transformation function might be:
or if you might need other extraction functions:
Example:
Now you might need to remove duplicate links. But this depends on the syntax and semantics of your graph description.