[英]Networkx BFS_Tree from adjacency list
I am new to networkx, and what I want to do is generate a graph from a .txt adjacency list (successful), the do a bfs_tree on said list.我是 networkx 的新手,我想要做的是从 .txt 邻接列表(成功)生成一个图形,在所述列表上做一个 bfs_tree。 The dfs_tree works, but bfs returns errors saying my source node is not in the graph.
dfs_tree 有效,但 bfs 返回错误,指出我的源节点不在图中。 I know why, I just need to know how to get it to work.
我知道为什么,我只需要知道如何让它工作。
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()
The data in the .txt file is: .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
If you read the text file the default type for the nodes is string.如果您阅读文本文件,节点的默认类型是字符串。 Therefore, you can resolve the issue by adding the node type, see docs of
read_adjlist
:因此,您可以通过添加节点类型来解决该问题,请参阅
read_adjlist
文档:
G = nx.read_adjlist("AL.txt", nodetype=int)
or by building the bfs_tree
from "1"
:或者通过从
"1"
构建bfs_tree
:
T2 = nx.bfs_tree(G, source="1")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.