使用Python中的Networkx从DAG中找到最长的加权路径?

时间:2015-06-19 10:57:29

标签: python algorithm graph weighted longest-path

我需要一种算法来查找有向无环图networkx.MultiDiGraph()中的最长加权路径。我的图形具有加权边缘,并且许多边缘具有空值作为加权。在networkx doc中,我找不到解决这个问题的方法。我的图表具有以下结构:

>>> print graph.nodes()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, 20, 21, 22, 25, 26, 'end']
>>> print graph.edges()
[(0, 'end'), (1, 0), (1, 10), (1, 5), (2, 1), (2, 11), (2, 6), (3, 2), (3, 12), (3, 7), (4, 8), (4, 3), (4, 13), (5, 'end'), (6, 5), (6, 15), (7, 16), (7, 6), (8, 17), (8, 7), (10, 'end'), (11, 10), (11, 20), (11, 15), (12, 16), (12, 11), (12, 21), (13, 17), (13, 12), (13, 22), (15, 'end'), (16, 25), (16, 15), (17, 16), (17, 26), (20, 'end'), (21, 25), (21, 20), (22, 26), (22, 21), (25, 'end'), (26, 25)]
>>> print graph.edge[7][16]
{1: {'weight': 100.0, 'time': 2}}
>>> print graph.edge[7][6]
{0: {'weight': 0, 'time': 2}}

我发现了她,但我在实施方面遇到了问题:

  1. networkx: efficiently find absolute longest path in digraph此解决方案没有权重。
  2. How to find the longest path with Python NetworkX?此解决方案将权重转换为否定值,但我的图表具有空值...而nx.dijkstra_path()不支持负值。
  3. 有没有人想到或找到类似问题的解决方案?

1 个答案:

答案 0 :(得分:0)

获取链接1中的解决方案并更改行:

pairs = [[dist[v][0]+1,v] for v in G.pred[node]] # incoming pairs

类似于:

pairs = [[dist[v][0]+edge['weight'],v] for u, edge in G[v][node] for v in G.pred[node]] # incoming pairs