【发布时间】:2021-12-29 14:15:58
【问题描述】:
我的问题是找到u 和v 之间的最短路径,它们是有向图中的节点并且图的边具有权重。
我尝试过使用NetworkX,但它太慢了(在 37202 个节点和 79264 个边的图表上平均 50 毫秒)。
igraph 似乎没有为 加权 最短路径提供 API。
还有其他可用的工具吗?
这是我正在使用的代码。 (test_graph.txt 只是图形定义,test_nodes.txt 包含用于测试的节点)
import networkx as nx
import random
from tqdm import tqdm
import time
G = nx.DiGraph()
with open("test_graph.txt") as f:
for l in f:
l = l.strip().split("\t")
G.add_edge(int(l[0]), int(l[1]), length=float(l[2]))
nodes = [int(i) for i in open("test_nodes.txt")]
N = 1000
for _ in tqdm(range(N)):
u, v = random.sample(nodes, 2)
cnt = 0
total = 0
try:
t = time.time()
nx.shortest_path(G, u, v, weight="length")
total += time.time() - t
cnt += 1
except nx.NetworkXNoPath:
pass
print(f"{cnt/N*100:.2f} found, average {total/cnt:.6f}s")
【问题讨论】:
标签: python python-3.x graph