好吧,我要介绍的解决方案有点老套,但我愿意接受更多优化的建议。
首先,我们将创建一个用于测试的虚拟图
import networkx as nx
G = nx.balanced_tree(2,4,create_using=nx.DiGraph())
下一步,我们会
dfs_tree
NetworkX的API(使用最新版本)并使用
depth_limit
属性提取树到深度
n
和
n+1
在哪里?
N+1个
是用户输入的深度(因为它在1开始索引深度)
T1 = nx.dfs_tree(G, source=0,depth_limit=3) #here n=3
T1_edges = list(T.edges())
#[(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6), (3, 8), (3, 7), (4, 9), (4, 10), (5, 11), (5, 12), (6, 13), (6, 14)]
对深度也一样
N+1个
T2 = nx.dfs_tree(G, source=0,depth_limit=4)
T2_edges =list(T2.edges())
#[(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6), (3, 8), (3, 7), (4, 9), (4, 10), (5, 11), (5, 12), (6, 13), (6, 14), (7, 16), (7, 15), (8, 17), (8, 18), (9, 19), (9, 20), (10, 21), (10, 22), (11, 24), (11, 23), (12, 25), (12, 26), (13, 27), (13, 28), (14, 29), (14, 30)]
现在把这两个列表的异或
edges_left = list(set(T1_edges).symmetric_difference(T2_edges))
#[(14, 30), (11, 23), (10, 21), (7, 16), (11, 24), (7, 15), (10, 22), (9, 20), (12, 25), (13, 28), (8, 17), (14, 29), (12, 26), (13, 27), (8, 18), (9, 19)]
这是3层的边缘。现在提取这些级别的节点
nodes_at_level = set([x[0] for x in edges_left])
#{7, 8, 9, 10, 11, 12, 13, 14}
然后使用
bfs_tree
在这些节点上提取树
for n in nodes_at_level:
tree = nx.bfs_tree(G, n)
print tree.edges() #Do whatever you want with those subgraphs
#[(7, 16), (7, 15)]
#[(8, 17), (8, 18)]
#[(9, 19), (9, 20)]
#[(10, 21), (10, 22)]
#[(11, 24), (11, 23)]
#[(12, 25), (12, 26)]
#[(13, 27), (13, 28)]
#[(14, 29), (14, 30)]