这似乎有两个问题。涉及networkx的部分我可以回答。
Graph:
有点迂腐(因为我在想象未来的人会在谷歌上搜索这个),这确实取决于您正在使用的图表类型。我们将从通用图表开始:
import networkx as nx
G = nx.path_graph(5)
G.add_edge(2, 8, weight=0.3) # A
G.add_edge(2, 8, weight=0.6) # B
G.add_edge(1, 8, weight=1.0)
for u, v, w in G.edges(data=True):
print(u, v, k)
...并考虑如果我们切换标记为A 和B 的行的顺序会发生什么:
import networkx as nx
G = nx.path_graph(5)
G.add_edge(2, 8, weight=0.6) # B
G.add_edge(2, 8, weight=0.3) # A
G.add_edge(1, 8, weight=1.0)
for u, v, w in G.edges(data=True):
print(u, v, k)
在这两种情况下:网络看起来都一样:
但是我们网络的参数在这两种情况下是不同的:
# A first
0 1 {}
1 2 {}
1 8 {'weight': 1.0}
2 3 {}
2 8 {'weight': 0.6}
3 4 {}
和
# B first
0 1 {}
1 2 {}
1 8 {'weight': 1.0}
2 3 {}
2 8 {'weight': 0.3}
3 4 {}
所以这里:答案是u、v 和k 是唯一的,shortest_path 返回的列表将是唯一的。
MultiDiGraph:
我 90% 确定这是问题要问的情况。在MultiDiGraph 中,节点仍由u、v 索引,但可以有多个权重k:
import networkx as nx
GM = nx.MultiDiGraph()
GM.add_edge(0, 2, weight=0.3)
GM.add_edge(0, 2, weight=0.15)
GM.add_edge(1, 2, weight=0.1)
GM.add_edge(0, 1, weight=0.1)
GM.add_edge(2, 3, weight=0.4)
GM.add_edge(2, 3, weight=0.5)
for u, v, w in GM.edges(data=True):
print(u, v, w)
path = nx.shortest_path(GM, source=0, target=3, weight='weight')
print(path)
# [0, 2, 3]
nx.shortest_path 返回的列表不明确,但重构最小权重路径非常简单:
for u, v in zip(path[0:], path[1:]):
edge_data = GM.get_edge_data(u, v)
min_weight = min([edge_data[edge]['weight'] for edge in edge_data])
print(f"{u}---({min_weight})---{v}")
结果:
0---(0.15)---2
2---(0.4)---3