0

我正在尝试定位地图最短路径的路线(具有权重/距离的连接节点)。

假设我有一个这样的哈希:

{"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 -> LA -> 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

4

1 回答 1

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"]

请注意,如果没有解决方案,则循环可能会永远运行。您可能希望通过对长度添加限制来限制它。

于 2013-09-04T12:32:22.630 回答