我正在启动一些 lua 脚本,似乎陷入了一个简单的问题。
我实际上是在尝试实现 Floyd-Warschall 算法来计算图的每个顶点之间的所有最短路径(http://en.wikipedia.org/wiki/Floyd –Warshall_algorithm 用于对该算法的简短解释)。它最初是用 python 编写的(这里是代码https://gist.github.com/DavidCain/4032399)。我的版本有点不同,为了让它适合我的主要代码,但基本上是一样的。
这是我的注释代码。每次我运行它时,我都会得到一个“尝试索引字段'?' (零值)”(我觉得解决方案很简单,但我似乎无法解决问题。任何帮助将不胜感激):
function adj(bodies) --returns, from a 1d array of vertices called "bodies", a square adjacency matrix (a matrix of size number_of_vertices x number_of_vertices that tells, with a ones, if vertices are connected, or with 'infs' if they are not connected)
n = table.getn(bodies)
dist = {}
for _,i in pairs(bodies) do
dist[i] = {}
for _,j in pairs(bodies) do
if i == j then
dist[i][j] = 0
end
if areConnected(i,j) == true then --areConnected is another function I wrote to see if, well, two particular vertices are actually connected. If they are, distance is 1, if not, distance is inf.
dist[i][j] = 1
else dist[i][j] = math.huge
end
end
end
return adjMatrix
end
function PhysicsDebugDraw:fw(adjMatrix) --I pass adjMatrix to this function
d = adjMatrix
for _,k in pairs(d) do
for _,i in pairs(d) do
for _,j in pairs(d) do
d[i][j] = math.min(d[i][j], d[i][k] + d[k][j]) -- the problem is here I suspect...
end
end
end
return d
end