python中的BFS到DFS八叉树转换

时间:2019-11-21 17:16:33

标签: python octree

我正在使用由第三方软件构建的八叉树。该软件报告了如何以广度优先的方式遍历树,但是我想以深度优先的方式遍历树。

对于我的应用程序(使用天体物理学应用程序的粒子数据构建网格),我倾向于根据“精化”列表来考虑八叉树,即对于未精化的单元,我们将:

False

对于一个精简为Oct的单元格,我们将:

True
False
False
False
False
False
False
False
False

我的目标是将以“广度优先”方式生成的refined列表转换为“深度优先”方式(在python中),但是对于从何处开始感到迷茫。

例如以下代码:

def construct_octree(refined=[True]):

    # Loop over subcells
    for subcell in range(8):

        # Insert criterion for whether cell should be sub-divided. Here we
        # just use a random number to demonstrate.
        divide = random.random() < 0.5

        # Append boolean to overall list
        refined.append(divide)

        # If the cell is sub-divided, recursively divide it further
        if divide:
            construct_octree(refined)

    return refined

oct = construct_octree()

将为深度优先遍历创建refined列表。

1 个答案:

答案 0 :(得分:0)

所以您正在使用hyperion?如前所述,树并不是天生就优先于深度或宽度。但是,hyperion对待它们的方式实际上是针对深度优先遍历而设置的。以列表格式考虑此八叉树:

refine3 = [True,       # 1
             False,    # 2
             False,    # 3
             True,     # 4
               False,  # 10
               False,  # 11
               False,  # ..
               False,  # ..
               False,  # 14
               False,  # 15
               False,  # 16
               False,  # 17
             False,    # 5
             False,    # 6
             False,    # 7
             True,     # 8
               False,  # 18
               False,  # 19
               False,  # 20
               False,  # ..
               False,  # ..
               False,  # ..
               False,  # ..
               False,  # 25
             False,    # 9
             ]

深度优先遍历为1,2,3,4,10,11,12 ...或图中的绿线: octree traversal

要做到这一点,您所需要做的就是:

for node in refine3:
    print(node)

也可以先进行宽度优先(橙色线),但这会更加复杂。