![](/img/trans.png)
[英]Using networkx bfs_tree to obtain a list of nodes of a directed graph in BFS order
[英]Networkx BFS_Tree from adjacency list
我是 networkx 的新手,我想要做的是从 .txt 邻接列表(成功)生成一个图形,在所述列表上做一个 bfs_tree。 dfs_tree 有效,但 bfs 返回错误,指出我的源节点不在图中。 我知道为什么,我只需要知道如何让它工作。
import networkx as nx
import matplotlib.pyplot as plt
G = nx.read_adjlist("AL.txt")
nx.draw(G, with_labels=True)
plt.show()
T = nx.dfs_tree(G)
nx.draw(T, with_labels=True)
plt.show()
T2 = nx.bfs_tree(G, source=1)
nx.draw(T2, with_labels=True)
plt.show()
.txt 文件中的数据是:
1 2 4 5
2 1 4 3
3 2 4 6
4 1 2 3 5 6 7
5 1 4 7 8
6 3 4 7 10
7 4 5 6 10 8
8 5 7 9
9 8 10
10 6 7 9
如果您阅读文本文件,节点的默认类型是字符串。 因此,您可以通过添加节点类型来解决该问题,请参阅read_adjlist
文档:
G = nx.read_adjlist("AL.txt", nodetype=int)
或者通过从"1"
构建bfs_tree
:
T2 = nx.bfs_tree(G, source="1")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.