["C","D","E"], "B" => ["C","F"], "C" =>-6ren">
gpt4 book ai didi

ruby - 打印 BFS 中的每个级别

转载 作者:数据小太阳 更新时间:2023-10-29 08:54:43 24 4
gpt4 key购买 nike

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

我有这样的东西:

$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

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

最佳答案

该解决方案需要检查您是否真的为给定节点打印了一些内容,这样我们就不会为不应该打印任何内容的节点添加额外的 \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

关于ruby - 打印 BFS 中的每个级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4290317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com