简体   繁体   English

networkx中的定向加权平衡树导入和最短路径

[英]Directed, weighted balanced tree import and shortest path in networkx

I have a balanced tree with branching factor 2 and height 100, and each edge has a weight given by a text file that looks like: 我有一个平衡的树,分支因子2和高度100,每个边都有一个由文本文件给出的权重,如下所示:

 73 41
 52 40 09
 26 53 06 34
 etc etc until row nr 99

ie: The edge weight from node 0 to 1 is 73, from 0 to 2 is 41, and from 1 to 3 is 52, etc. 即:从节点0到1的边缘权重是73,从0到2是41,从1到3是52,等等。

I wish to find the shortest path (with the corresponding edge weight sum) from the root to the end of the tree. 我希望找到从树的根到末尾的最短路径(具有相应的边权重和)。 As far as I understand, this can be done by multiplying all edge weights by -1 and using the Dijkstra algorithm in Networkx. 据我所知,这可以通过将所有边权重乘以-1并使用Networkx中的Dijkstra算法来完成。

  1. Is the algorithm choice correct? 算法选择是否正确?
  2. How do I "easily" import this data set into a Networkx graph object? 如何“轻松”将此数据集导入Networkx图形对象?

( PS: This is Project Euler Problem 67 , finding the maximum sum in a triangle of numbers. I have solved the question with recursion with memoization, but I want to try and solve it with the Networkx package. ) PS:这是项目欧拉问题67 ,找到数字三角形的最大总和。我已经通过memoization递归解决了问题,但我想尝试用Networkx包解决它。

Is the algorithm choice correct? 算法选择是否正确?

Yes. 是。 You can use positive weights, and call nx.dijkstra_predecessor_and_distance to get the shortest paths starting from the root node, 0 . 您可以使用正权重,并调用nx.dijkstra_predecessor_and_distance以获取从根节点0开始的最短路径。


How do I "easily" import this data set into a Networkx graph object? 如何“轻松”将此数据集导入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()

I'm not sure I quite understand the input format. 我不确定我是否完全理解输入格式。 But something similar to this should work: 但类似的东西应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM