我有一个平衡的树,分支因子2和高度100,每个边都有一个由文本文件给出的权重,如下所示:
73 41
52 40 09
26 53 06 34
etc etc until row nr 99
即:从节点0到1的边权重是73,从0到2是41,从1到3是52,等等。
我希望找到从树的根到末尾的最短路径(具有相应的边权重和)。据我所知,这可以通过将所有边权重乘以-1并使用Networkx中的Dijkstra算法来完成。
( PS:这是项目Euler Problem 67,找到数字三角形的最大总和。我已经通过memoization递归解决了问题,但我想尝试用Networkx解决它包。)
答案 0 :(得分:4)
算法选择是否正确?
是。您可以使用正权重,并调用nx.dijkstra_predecessor_and_distance以从根节点0
开始获取最短路径。
如何“轻松”将此数据集导入Networkx图形对象?
import networkx as nx
import matplotlib.pyplot as plt
def flatline(iterable):
for line in iterable:
for val in line.split():
yield float(val)
with open(filename, 'r') as f:
G = nx.balanced_tree(r = 2, h = 100, create_using = nx.DiGraph())
for (a, b), val in zip(G.edges(), flatline(f)):
G[a][b]['weight'] = val
# print(G.edges(data = True))
pred, distance = nx.dijkstra_predecessor_and_distance(G, 0)
# Find leaf whose distance from `0` is smallest
min_dist, leaf = min((distance[node], node)
for node, degree in G.out_degree_iter()
if degree == 0)
nx.draw(G)
plt.show()
答案 1 :(得分:3)
我不确定我是否完全理解输入格式。但类似的东西应该有效:
from itertools import count
import networkx as nx
adj ="""73 41
52 40 09
26 53 06 34"""
G = nx.Graph()
target = 0
for source,line in zip(count(),adj.split('\n')):
for weight in line.split():
target += 1
print source,target,weight
G.add_edge(source,target,weight=float(weight))
# now call shortest path with weight="weight" and source=0