我做了一个简单的网络:
import networkx as nx
G=nx.Graph()
G.add_node("a")
G.add_nodes_from(["b","c"])
G.add_edge(1,2)
edge = ("d", "e")
G.add_edge(*edge)
edge = ("a", "b")
G.add_edge(*edge)
print("Nodes of graph: ")
print(G.nodes())
print("Edges of graph: ")
print(G.edges())
# adding a list of edges:
G.add_edges_from([("a","c"),("c","d"), ("a",1), (1,"d"), ("a",2)])
nx.draw(G)
plt.show() # display
我想列出所有节点从相同节点开始并以相同节点结束的所有可能路径。例如,从节点“ a”开始到节点“ a”可以是:
a-2-1-a,a-c-b-1-a,....
从节点“ 2”开始到节点“ 2”结束可以是:
2-a-1-2、2-1-d-c-a-2,....
我该怎么办?
答案 0 :(得分:1)
在同一节点开始和结束的路径称为循环。由于可以重复循环,因此每当您有一个循环时,可能的路径数都是无限的。通过调用nx.cycle_basis(G)
,可以找到构成G循环基础的循环列表。
如果希望显式计算所有路径而不重复节点,则可以按以下步骤进行操作:
import networkx as nx
G=nx.Graph()
G.add_edges_from([("d", "e"), ("a", "b"), ("a","c"), ("c","d"), ("a",1), (1,"d"), ("a",2), (1,2)])
node_to_cycles = {}
for source in G.nodes():
paths = []
for target in G.neighbors(source):
paths += [l + [source] for l in list(nx.all_simple_paths(G, source=source, target=target)) if len(l) > 2]
node_to_cycles[source] = paths
print(node_to_cycles['a'])
此实现基于nx.all_simple_paths
。由于简单路径的每个节点只有一个实例,因此我们搜索到节点的每个邻居的路径,然后将节点本身串联起来。