2

所以,我可以遍历列表,但我不能打印出每个级别。不知道怎么做。

我有这样的事情:

$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

我喜欢这样打印

A
C D E
B F

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

4

1 回答 1

3

The solution required checking to see if you'd actually printed something for a given node so that we didn't add an extra \n for nodes that shouldn't have printed anything.

Solution

We add the appropriate \n's as needed.

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
于 2010-11-27T06:40:14.507 回答