【发布时间】:2022-08-17 22:08:28
【问题描述】:
你好,我有一个看起来像这样的 dag
我想从根部开始旅行并打印输出,例如
1 6
2 3
4
5
我尝试过这样的事情,但它仍然无法正常工作。有人可以给我一个关于这种算法应该是什么样子或这种图遍历的名称的提示吗?
from typing import List
class Node:
def __init__(self, value, children) -> None:
super().__init__()
self.value = value
self.children = children
@staticmethod
def create(value, *parents):
node = Node(value, [])
if parents is not None:
for parent in parents:
parent.children.append(node)
return node
def travel(roots: List[Node], visited: List[Node]):
print(\" \".join([str(r.value) for r in roots]))
visited += roots
all_children = []
for r in roots:
if r.children:
for c in r.children:
if c not in visited:
all_children.append(c)
if all_children:
travel(all_children, visited)
if __name__ == \'__main__\':
root = Node.create(1)
root2 = Node.create(6)
roots = [root, root2]
n2 = Node.create(2, root)
n3 = Node.create(3, root)
n4 = Node.create(4, n2, n3, root2)
n5 = Node.create(5, n4)
travel(roots, [])
-
你如何决定
[2,3]和4的优先级?因为两者都与根的距离为 1? -
4 取决于 2,3 所以它需要等待它们
-
我想你正在寻找topological sort
标签: python algorithm graph directed-acyclic-graphs