python - 计算由边字典定义的树图的深度
问题描述
我有字典,它将单个节点映射到它们连接的节点列表。我需要生成一个树形图(不是二进制),然后计算它的深度(从上到下最长的方式)。做这个的最好方式是什么?
例子:
graph = {
1 : [],
2 : [],
3 : [2, 4],
4 : [1, 5],
5 : []
}
答案 = 3(您需要通过最多 3 个节点才能到达底部)
解决方案
这可以使用networkx来完成:
代码:
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
推荐阅读
- reactjs - 从 electron desktopCapturer 生成直播 url
- blockchain - satoshi是如何编程的?
- pdf - How to change font color and fontsize of FreeTextAnnotations (itext 7)?
- python - How to sort rows in pandas in place for given group?
- javascript - 如何通过JS检查表中的值
- php - Wordpress - 比较日期 - 十月大于十一月(Ymd)
- python - 无法使用 Scrapy 连接“str”和“NoneType”对象
- java - JavaFX——按键事件被按钮中断
- webpack - 如何获取不同 webpack 条目的 URL?
- d3.js - D3 共享缩放/过渡