我正在尝试定位地图最短路径的路线(具有权重/距离的连接节点)。
假设我有一个这样的哈希:
{"A"=>{"B"=>1, "E"=>1}, "B"=>{"A"=>1, "C"=>1, "F"=>1}, "C"=>{"B"=>1, "D"=>1, "G"=>1}, "D"=>{"C"=>1, "H"=>1}, "E"=>{"F"=>1, "A"=>1, "I"=>1}, "F"=>{"E"=>1, "G"=>1, "B"=>1, "J"=>1}, "G"=>{"F"=>1, "H"=>1, "C"=>1, "K"=>1}, "H"=>{"G"=>1, "D"=>1, "L"=>1}, "I"=>{"J"=>1, "E"=>1, "M"=>1}, "J"=>{"I"=>1, "K"=>1, "F"=>1, "N"=>1}, "K"=>{"J"=>1, "L"=>1, "G"=>1, "O"=>1}, "L"=>{"K"=>1, "H"=>1, "P"=>1}, "M"=>{"N"=>1, "I"=>1}, "N"=>{"M"=>1, "O"=>1, "J"=>1}, "O"=>{"N"=>1, "P"=>1, "K"=>1}, "P"=>{"O"=>1, "L"=>1}}
现在我想从这个哈希中遍历并创建一条路径。例如:
从源 A 到目的地:L
输出应该是:要么A -> E -> I -> J -> K -> L
或A -> B -> C -> D -> H -> L
。
这是我写的函数:
def find_path(src, dst, init = [])
path = [src]
neighbors = self.neighbors(src)
puts "src: #{src}"
puts "dst: #{dst}"
# puts "node: #{node}"
puts "init: #{init}"
puts "path: #{path}"
puts "----\n"
if neighbors.include?(dst)
path.push(dst)
else
path.push(@nodes[src].keys.map{|k| k unless init.flatten.include? k }.reject(&:blank?).each{|key| self.find_path(key, dst, init << path) } )
end
return path
end
但是,这仅打印: ["A", ["B", "E"]]
哪个不是所需的输出,有人可以告诉我如何进行这项工作吗?谢谢。
更新:这用于定位地图最短路径的路线(具有权重/距离的连接节点)。以下是我试图在这个问题中实现的详细信息:https ://gist.github.com/suryart/6439102