如何在树模型中获取所有可能的路径

时间:2014-03-19 16:16:03

标签: ruby algorithm recursion tree tree-traversal

我正在寻找一种方法来使用Ruby获取树/网络模型的所有可能路径。

我的模特示例:

Network

我需要的是所有可能路径的列表:

  1. ACG
  2. ACH
  3. ADG
  4. ADH
  5. ABEG
  6. ABEH
  7. ABFG
  8. ABFH
  9. 每个节点都有一个子节点列表。子节点数可以是0..x

    似乎非常微不足道,但我还没有办法做到这一点。有任何想法吗?提前谢谢!




    更新

    我设法得到了相同的结果:

    def get_paths(ret_data, list = "")
      children = get_children
      list += description
    
      if children.count == 0
        ret_data.push(list)
      end
    
      children.each do |c|
        c.get_paths(ret_data, list)
      end
    end
    
    data = []
    first_node.get_paths(data)
    
    data ====>
    
    [
     "ACG",
     "ACH",
     "ADG",
     "ADH",
     "ABEG",
     "ABEH",
     "ABFG",
     "ABFH"
    ]
    

    结果没问题,但如果我将节点的描述推送到get_paths方法中的数组中,结果很奇怪:

     def get_paths(ret_data, list = [])
      children = get_children
    
       list << description
    
       if children.count == 0
        ret_data.push(list)
       end
    
       children.each do |c|
         c.get_paths(ret_data, list)
       end
     end
    
     data = []
     first_node.get_paths(data)
    
     data ====>
    
     [
      [
        "A",
        "C",
        "G",
        "H",
        "D",
        "G",
        "H",
        "B",
        "E",
        "G",
        "H",
        "F",
        "G",
        "H"
    ],
    [
        "A",
        "C",
        "G",
        "H",
        "D",
        "G",
        "H",
        "B",
        "E",
        "G",
        "H",
        "F",
        "G",
        "H"
    ],
    [data like above],[data like above]....,
    [
        "A",
        "C",
        "G",
        "H",
        "D",
        "G",
        "H",
        "B",
        "E",
        "G",
        "H",
        "F",
        "G",
        "H"
    ]]
    
    number of paths ok (8), but data inside paths wrong
    

    将节点描述推送到数组时会发生什么?

1 个答案:

答案 0 :(得分:1)

您应该发布一些代码,显示树的表示方式。在这里,我刚刚发明了一个使用哈希的结构。

h={:name=>"H", :children=>[]}
g={:name=>"G", :children=>[]}
f={:name=>"F", :children=>[g,h]}
e={:name=>"E", :children=>[g,h]}
d={:name=>"D", :children=>[g,h]}
c={:name=>"C", :children=>[g,h]}
b={:name=>"B", :children=>[e,f]}
a={:name=>"A", :children=>[b,c,d]}

def paths(node,path='',&proc)
  if node[:children].empty?
    proc.call(path+node[:name])
  else
    node[:children].each{|c| paths(c,path+node[:name],&proc)}
  end
end

paths(a){|path|
  puts path
}

这是一个基本的深度优先搜索,跟踪到目前为止的路径,并在叶子节点上调用给定的块。