您可以使用 networkX bellman_ford 方法来查找比给定最小值更长的路径。为此,您需要权重设置为-1 的有向图(或图)G。
以下代码基于此线程。
import networkx as nx
import matplotlib.pyplot as plt
data = (('a','b',50), ('b','c',60), ('b','e',25),
('e','f',20), ('z','n',10), ('x','m',25),
('v','p',15))
G = nx.DiGraph()
for node1, node2, weight1 in data:
G.add_edge(node1, node2, weight=-1)
min_lenght = 2
F = nx.DiGraph() #filtered graphs
# check all edges with bellman_ford
for u, v in G.edges():
vals, distances = nx.bellman_ford(G, u)
if min(distances.values()) < - min_lenght:
for u, v in vals.items():
if v:
F.add_edge(v, u)
nx.draw(F)
plt.show()
这将产生唯一符合要求的图表:
请注意,这是确定具有最长路径(就距离而言)的图形的一般方法的简化。因此,如果您创建包含权重的图表,您可以在更改权重的符号后应用 bellman ford:
G = nx.DiGraph()
for node1, node2, weight1 in data:
G.add_edge(node1, node2, weight=weight1)
min_lenght = 100
H = nx.DiGraph(G) # intermediate graph
# change sign of weights
for u, v in H.edges():
H[u][v]['weight'] *= -1
# check all edges with bellman_ford
for u, v in G.edges():
vals, distances = nx.bellman_ford(H, u)
if min(distances.values()) < - min_lenght:
#--- whatever ----