1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| local contains = function(list, element) for i = 1, #list do if list[i] == element then return true end end return false end
local findMinDisNodeNotVisited = function(dis2startNode) local minDis = math.maxinteger local minDisNode = nil for node, visitedAndDis in pairs(dis2startNode) do if not visitedAndDis[1] and visitedAndDis[2] >= 0 then if visitedAndDis[2] < minDis then minDis = visitedAndDis[2] minDisNode = node end end end return minDisNode end
local map = {} map["v1"] = {["v2"] = 2, ["v3"] = 8, ["v4"] = 3} map["v2"] = {["v5"] = 4, ["v6"] = 7} map["v3"] = {["v1"] = 8, ["v6"] = 1, ["v7"] = 2} map["v4"] = {["v7"] = 2} map["v5"] = {["v8"] = 3} map["v6"] = {["v3"] = 1, ["v8"] = 1, ["v9"] = 2} map["v7"] = {["v3"] = 2, ["v9"] = 8} map["v8"] = {["v5"] = 3, ["v6"] = 1, ["v9"] = 3} map["v9"] = {["v6"] = 2, ["v7"] = 8, ["v8"] = 3}
local dis2startNode = {} local preNode = {}
local startNode = "v1" local endNode = "v9" local nodeCount = 0 local curNode = startNode local visitedNodeCount = 0
for k, v in pairs(map) do nodeCount = nodeCount + 1 dis2startNode[k] = {false, -1} end dis2startNode[startNode][2] = 0
repeat curNode = findMinDisNodeNotVisited(dis2startNode) dis2startNode[curNode][1] = true visitedNodeCount = visitedNodeCount + 1 local neighborList = map[curNode] for neighborNode, disFromCurNode2neighborNode in pairs(neighborList) do if not dis2startNode[neighborNode][1] then local startNode2curNode = dis2startNode[curNode][2] local startNode2neighborNode = dis2startNode[neighborNode][2] local isShortPath = startNode2neighborNode < 0 or startNode2curNode + disFromCurNode2neighborNode < startNode2neighborNode
if isShortPath then local newDis = startNode2curNode + disFromCurNode2neighborNode dis2startNode[neighborNode][2] = newDis preNode[neighborNode] = curNode end end end until(visitedNodeCount == nodeCount)
local node = endNode local path = {node} local length = 0 while true do local pre_node = preNode[node] length = length + map[pre_node][node] node = pre_node table.insert(path, node) if node == startNode then break end end
local output = "minimum distance from "..startNode.." to "..endNode .. " is "..length..". path = " for i = #path, 1, -1 do output = output .. path[i] .. " -> " end print(string.sub(output, 1, #output - 4))
|