【发布时间】:2016-01-19 23:04:24
【问题描述】:
在我的代码上工作了一段时间后,优化了最明显的东西,我得到了这样的结果:
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
--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)}
npath[#npath+1] = v
if v == finish then
--If we reach the end add the path
return npath
else
--Otherwise add the shortest part extending from this node
paths[#paths+1] = FindPath(v, finish, npath) --NOTED HERE
end
end
end
--Find and return the shortest path
if #paths > 0 then
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
end
问题是,注释的行出现某种游戏脚本超时错误(我认为这是因为没有屈服的大规模递归)。我也觉得一旦这个问题得到解决,即使在 pacman 板的规模上,它也可能会相当慢。有没有办法可以进一步优化它,或者我可以研究类似的更好的方法?
更新:由于效率低下,我最终决定放弃我的算法,并实现了一个用于寻路的 Dijkstra 算法。任何对源代码感兴趣的人都可以在这里找到:http://pastebin.com/Xivf9mwv
【问题讨论】:
标签: performance optimization lua path-finding roblox