我正在尝试找到地图最短路径的路线(连接的节点有重量/距离)。
我们假设我有这样的哈希:
{"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
答案 0 :(得分:2)
原始哈希:
h = {"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}}
转换原始哈希,因为它的格式很糟糕:
h.keys.each{|k| h[k] = h[k].keys}
h.default = []
方法:
def find_path h, src, dst
paths = [[src]]
loop do
paths = paths.flat_map do |path|
h[path.last].map do |nekst|
a = [*path, nekst]
a.last == dst ? (return a) : a
end
end
end
end
试一试:
find_path(h, "A", "L")
# => ["A", "B", "C", "D", "H", "L"]
请注意,如果没有解决方案,那么循环可能会永远运行。您可能希望通过添加长度限制来限制它。