DFS遍历深度嵌套散列 [英] DFS traversal of a deeply nested hash

查看:132
本文介绍了DFS遍历深度嵌套散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过这个问题在Ruby中递归地遍历一个Hash

p>

但是我仍然无法做到这一点。任何人都可以请帮助(也解释)。

输入哈希值:

  { 。 => {foo=> {hello=> {},world=> {}},bar=> {}}} 

我只需要遍历它而不是搜索任何东西

解决方案

如果所有的值都是散列值,那么这将起作用:

  hash = {。 => {foo=> {hello=> {},world=> {}},bar=> {}}} 

def遍历(hash,depth = 0)
hash.each {| key,value |
puts#{depth}#{key}
遍历(值,深度+1)
}
结束

遍历(散列)$



$ b

输出: c $ c> 0。
1 foo
2 hello
2 world
1 bar


I have seen this question Traversing a Hash Recursively in Ruby

However I am still not able to achieve this. Can anyone please help (also explain).

Input hash:

{"." => {"foo" => {"hello" => {}, "world" => {}}, "bar" => {}}}

I just need to traverse it and not search for anything

解决方案

If all values are hashes, this would work:

hash = {"." => {"foo" => {"hello" => {}, "world" => {}}, "bar" => {}}}

def traverse(hash, depth = 0)
  hash.each { |key, value|
    puts "#{depth} #{key}"
    traverse(value, depth + 1)
  }
end

traverse(hash)

Output:

0 .
1 foo
2 hello
2 world
1 bar

这篇关于DFS遍历深度嵌套散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆