使用Floyd-Warshall算法进行路径重建。
2014-2-3 4:13:1
收藏:0
阅读:118
评论:0
我正在尝试从我在Lua中实现的Floyd-Warshall算法中重构两个顶点之间的最小成本路径。
这是我到目前为止写的内容:
function shallow_copy(g)
local h = {}
for k, v in pairs(g) do
h[k] = v
end
return h
end
function fw(g) -- g is an adjacency matrix representing the graph
local d = shaloow_copy(g)
for k = 1, #d do
for i = 1, #d do
for j = 1, #d do
d[i][j] = math.min(d[i][j], d[i][k] + d[k][j])
end
end
end
return d
end
这些函数给我一个矩阵,其中包含我图形中每对顶点之间分离长度(边数),这非常方便。
现在,我需要知道任何给定顶点之间的实际路径。维基百科提供了伪代码,但–作为新手–我不知道如何实现它。
这是维基百科文章中提供的伪代码(https://en.wikipedia.org/wiki/Floyd-Warshall_algorithm#Path_reconstruction):
let dist be a |V| × |V| array of minimum distances initialized to ∞ (infinity)
let next be a |V| × |V| array of vertex indices initialized to null
procedure FloydWarshallWithPathReconstruction ()
for each vertex v
dist[v][v] ← 0
for each edge (u,v)
dist[u][v] ← w(u,v) // the weight of the edge (u,v)
for k from 1 to |V|
for i from 1 to |V|
for j from 1 to |V|
if dist[i][k] + dist[k][j] < dist[i][j] then
dist[i][j] ← dist[i][k] + dist[k][j]
next[i][j] ← k
function Path (i, j)
if dist[i][j] = ∞ then
return "no path"
var intermediate ← next[i][j]
if intermediate = null then
return " " // the direct edge from i to j gives the shortest path
else
return Path(i, intermediate) + intermediate + Path(intermediate, j)
有人知道如何在lua中实现这个伪代码吗?我需要重新编写我的短lua代码还是可以将此伪代码某些方式合并到我已经拥有的代码中?
干杯!
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法