gpt4 book ai didi

graph - lisp 中的邻接矩阵/Floyd/Warshall

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:46 25 4
gpt4 key购买 nike

显然我的老师认为即使我们没有时间学习东西(也没有足够的示例)我们应该继续前进,所以我现在需要知道如何在 clisp 中制作 Floyd-Warshall 和 Warshall 的算法。

正如我对 prolog 所做的那样,我的问题是从图中生成邻接矩阵,在这种情况下它将是列表的列表,例如:

((A B) (A C) (A D) (B C) (C D))

应该生成:

((0 1 1 1) (1 0 1 9) (1 1 0 1) (1 9 1 0))

我有这个:

(defun floyd(graph)
(setf l (length graph))
(setf mat (matrix l graph))
)

(defun matrix(l graph)
(setf matrix (make-array (list l l)))
(dotimes (i l)
(dotimes (j l)
(if (= i j)
(setf (aref matrix i j) 0)
(setf (aref matrix i j) ???)
)
)
)
matrix
)

非常感谢任何帮助。

另外,有点跑题了:如果我能解决我自己的问题,我是否应该为了得到一个已回答的问题而回复自己?

最佳答案

我将 Wikipedia 伪代码转换为具有类型声明的 Common Lisp。返回类型声明是非标准的,我使用了 SBCL。我想这不会运行,但它可能会让您了解 Lisp 代码应该是什么样子。

(defparameter *n* 5)
(defparameter *path*
(make-array (list *n* *n*)
:element-type '(unsigned-byte 64)))


(defun floyd-warshall (path)
(declare (type (simple-array (unsigned-byte 64) 2) path)
(values (simple-array (unsigned-byte 64) 2) &optional))
(destructuring-bind (y x) (array-dimensions path)
(unless (= y x)
(break "I expect a square matrix, not ~ax~a." x y))
(macrolet ((p (j i)
`(aref path ,j ,i)))
(dotimes (k x)
(dotimes (i x)
(dotimes (j x)
(setf (p j i)
(min (p j i) (+ (p k i)
(p j k)))))))))
path)

注1:如果你有一个 3D 体积图像,你应该有这样的索引(aref vol k j i) 其中 k 索引 z、j y 和 i x 方向。那样在 SBCL 和大概所有其他实现中,切片在内存中是连续的。

注2:macrolet 可以节省大量的输入。还要看看这个漂亮的库中 with-arrays 的实现:git://github.com/nikodemus/raylisp.git/objects/box.lisp

关于graph - lisp 中的邻接矩阵/Floyd/Warshall,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6116793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com