用lua语言实现一下代码从确认起点出发遍历所有点的最短路径代码
以下是使用Lua语言实现的Dijkstra算法来求解从起点出发的最短路径的代码示例:
-- 图数据结构
local graph = {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
}
-- 获取图中的顶点数量
local function getVertexCount(graph)
return #graph
end
-- 找到距离数组中最小距离的顶点
local function findMinDistance(distance, visited)
local minDistance = math.huge
local minIndex = -1
for i = 1, #distance do
if not visited[i] and distance[i] < minDistance then
minDistance = distance[i]
minIndex = i
end
end
return minIndex
end
-- 打印最短路径
local function printPath(parent, vertex)
if parent[vertex] == -1 then
io.write(vertex, " ")
return
end
printPath(parent, parent[vertex])
io.write(vertex, " ")
end
-- Dijkstra算法
local function dijkstra(graph, start)
local vertexCount = getVertexCount(graph)
local distance = {}
local visited = {}
local parent = {}
-- 初始化距离数组、访问数组和父节点数组
for i = 1, vertexCount do
distance[i] = math.huge
visited[i] = false
parent[i] = -1
end
-- 设置起点的距离为0
distance[start] = 0
-- 找到最短路径
for _ = 1, vertexCount - 1 do
local u = findMinDistance(distance, visited)
visited[u] = true
for v = 1, vertexCount do
if not visited[v] and graph[u][v] ~= 0 and distance[u] + graph[u][v] < distance[v] then
distance[v] = distance[u] + graph[u][v]
parent[v] = u
end
end
end
-- 打印最短路径和距离
for i = 1, vertexCount do
if i ~= start then
io.write("最短路径从 ", start, " 到 ", i, " 的路径为:")
printPath(parent, i)
io.write(",距离为 ", distance[i], "\n")
end
end
end
-- 测试
dijkstra(graph, 1)
这里的graph变量表示图的数据结构,其中的数字表示边的权重。dijkstra函数接受一个图和起点作为参数,并计算出从起点到所有其他顶点的最短路径。最后的测试代码会输出从起点到其他顶点的最短路径和距离
原文地址: https://www.cveoy.top/t/topic/hIcA 著作权归作者所有。请勿转载和采集!