【问题标题】:Directed, weighted balanced tree import and shortest path in networkxnetworkx中的定向加权平衡树导入和最短路径
【发布时间】:2012-11-24 22:01:32
【问题描述】:

我有一个分支因子为 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 算法来完成。

  1. 算法选择是否正确?
  2. 如何“轻松”将此数据集导入 Networkx 图形对象?

(PS:这是 Project Euler Problem 67,在数字三角形中找到最大和。我已经通过记忆递归解决了这个问题,但我想尝试使用 Networkx 包解决它。 )

【问题讨论】:

  • 我不熟悉 Networkx,但如果没记错的话,Dijkstra 的算法需要非负边权重。

标签: python networkx


【解决方案1】:

算法选择正确吗?

是的。您可以使用正权重,并调用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()

【讨论】:

    【解决方案2】:

    我不确定我是否完全理解输入格式。但是类似的东西应该可以工作:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多