试图找到最短的路径

时间:2016-01-17 01:44:22

标签: lua roblox

所以我有以下代码,我认为它会通过节点递归,一旦达到目标,返回最短的代码。但是我得到Stack Overflow。

注意: GetConnectedParts是Part的一种方法,当前设置返回每个可访问节点。

注意2: 从开始到结束都有一条路径,实际上是多条路径。

我的代码在这里,感谢您提供的任何帮助:

function FindPath(start, finish, path)
    --Define a table to hold the paths
    local paths = {}
    --Make a default argument
    path = path or {start}
    --Loop through connected nodes
    for i,v in ipairs(start:GetConnectedParts()) do --Overflow occurs here
        --Determine if backtracking
        local loop = false
        for i,vv in ipairs(path) do
            if v == vv then
                loop = true
            end
        end
        if not loop then
            --Make a path clone
            local npath = {unpack(path)}
            if v == finish then
                --If we reach the end add the path
                paths[#paths+1] = npath
            else
                --Otherwise add the shortest part extending from this node
                paths[#paths+1] = FindPath(v, finish, npath)
            end
        end
    end
    --Find and return the shortest path
    local lengths = {}
    for i,v in ipairs(paths) do
        lengths[#lengths+1] = #v
    end
    local least = math.min(unpack(lengths))
    for i,v in ipairs(paths) do
        if #v == least then
            return v
        end
    end
end

1 个答案:

答案 0 :(得分:0)

哇,哇。我的问题实际上很容易解决。我没有将部件放在路径本身内。对不起,感到困惑。

相关问题