打印BFS中的每个级别

时间:2010-11-27 05:43:36

标签: ruby breadth-first-search

所以,我可以遍历列表,但我无法打印出每个级别。不确定如何。

我有这样的事情:

$list = {
  "A" => ["C","D","E"],
  "B" => ["C","F"],
  "C" => ["A","B","D","F","E"],
  "D" => ["A","C","E"],
  "E" => ["A","C","D"],
  "F" => ["B","C"]
 }


def BFS2()
  queue = ["A"]
  visited = {"A"=>true}
  print "A "
    while(!queue.empty?)
      node = queue.pop()
      $list[node].each do |child|
        if visited[child] != true then
           print "#{child} "
           queue.push(child)
           visited[child] = true
         end
      end
    end
end

而不是像

那样打印
A C D E B F

id喜欢将其打印出来

A
C D E
B F

我尝试了一些不同的东西,但我似乎无法得到它。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

该解决方案需要检查您是否确实为给定节点打印了某些内容,以便我们不会为不应该打印任何内容的节点添加额外的\n

解决方案

我们根据需要添加适当的\n

def BFS2()
  queue = ["A"]
  visited = {"A"=>true}
  puts "A "
    while(!queue.empty?)
      do_print = false
      node = queue.pop()
      $list[node].each do |child|
        if visited[child] != true then
           print "#{child} "
           queue.push(child)
           visited[child] = true
           do_print = true
        end
      end
      if do_print == true
        print "\n "
      end
    end
end