Python 计算由边字典定义的树图的深度
我有一个字典,它将单个节点映射到它们所连接的节点列表。我需要生成一个树形图(不是二进制的),然后计算它的深度(从上到下的最长路径)。最好的方法是什么 示例:Python 计算由边字典定义的树图的深度,python,dictionary,math,tree,graph-theory,Python,Dictionary,Math,Tree,Graph Theory,我有一个字典,它将单个节点映射到它们所连接的节点列表。我需要生成一个树形图(不是二进制的),然后计算它的深度(从上到下的最长路径)。最好的方法是什么 示例: graph = { 1 : [], 2 : [], 3 : [2, 4], 4 : [1, 5], 5 : [] } Answer=3(您最多需要通过3个节点才能到达底部)这可以通过以下方式完
graph = {
1 : [],
2 : [],
3 : [2, 4],
4 : [1, 5],
5 : []
}
Answer=3(您最多需要通过3个节点才能到达底部)这可以通过以下方式完成:
代码:
输出:
import networkx as nx
from networkx.algorithms.dag import dag_longest_path
graph = {
1 : [],
2 : [],
3 : [2, 4],
4 : [1, 5],
5 : []
}
#Create directed graph
G = nx.DiGraph(graph)
#Find longest path in tree:
path = dag_longest_path(G)
>>> path
[3, 4, 5]
>>> len(path)
3