2

I am trying to find the longest path of a DAG from vertex 0. After searching on Stackoverflow, I understand that I can invert the weighting of the edges and use the Bellman Ford algorithm to find the longest path. However, I don't fully understand how this works.

My graph however has no weighting (all are equal), I assume I should just set to -1?

I am using networkx and python to solve this. Here is my Bellman code:

def Bellman(G):
    pred, dist = nx.bellman_ford(G, 0, weight='-1')
    print(dist)

No matter what weight I set, I still get the lowest distance for every node from 0. Where am I going wrong?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
ForeverLearning
  • 1,027
  • 1
  • 12
  • 30

1 Answers1

2

According to the networkx documentation, the weight parameter to bellamn_ford is the key of an edge attribute which contains the weight. I guess by setting it to the non-existing edge attribute '-1', it does not consider any weights. What you will have to do to make this work is creating an edge attribute that is set to -1 for all edges:

for n in G:
  for nbr in G[n]:
    G[n][nbr]['myWeight'] = -1

and then call Bellman-Ford using this attribute as weights:

pred, dist = nx.bellman_ford(G, 0, weight='myWeight')

Note that instead of using a "custom" attribute like 'myWeight', you could also set the default attribute 'weight' to -1 and then call Bellman-Ford without having to explicitly specify the weight-Parameter.

matz
  • 626
  • 6
  • 18
  • 1
    Just a clarification: either to do G[n][nbr]['weight'] instead of 'myWeight' so that that you can call nx.bellman_ford(G,0) without specifying the weight parameter as it is 'weight' by default. Or you have to call as follows: nx.bellman_ford(G,0,weight='myWeight']) – Abdallah Sobehy Oct 15 '15 at 09:39
  • 1
    @AbdallahSobehy thank's for pointing this out. I've included this clarification into the answer. – matz Oct 15 '15 at 09:53
  • @matz and I have to invert the result again to get the actual lengths to each node yes? – ForeverLearning Oct 15 '15 at 20:05
  • @ForeverLearning yes -- the `dist` returned by the `bellman_ford` contains the weights summed up along the path, which will be negative in this case. – matz Oct 16 '15 at 06:14