pythonnetworkxfloyd-warshall

Networkx Floyd Warshall algorithm giving wrong distance


I'm trying to find the shortest distance between all sets of vertices in python, and I'm using the Floyd Warshall alg. However, it is (most definitely) giving me the wrong matrix.

Here's my code:

import networkx as nx
test = nx.barbell_graph(4,1)
nx.draw(test, with_labels = True)
testDist = nx.floyd_warshall_numpy(test)
print(testDist)

Now, the output (see below) shows wrong distances from node 8 (as seen by entries in the rightmost column/bottommost row), which is clearly wrong. I'm probably missing something trivial but am unable to understand what's going wrong. Here's the graph

[[0. 1. 1. 1. 3. 4. 4. 4. 2.]
 [1. 0. 1. 1. 3. 4. 4. 4. 2.]
 [1. 1. 0. 1. 3. 4. 4. 4. 2.]
 [1. 1. 1. 0. 2. 3. 3. 3. 1.]
 [3. 3. 3. 2. 0. 1. 1. 1. 1.]
 [4. 4. 4. 3. 1. 0. 1. 1. 2.]
 [4. 4. 4. 3. 1. 1. 0. 1. 2.]
 [4. 4. 4. 3. 1. 1. 1. 0. 2.] 
 [2. 2. 2. 1. 1. 2. 2. 2. 0.]]

Solution

  • I imagine that what's throwing you off here is that the nodes aren't ordered from 0 to 8:

    In [13]: test.nodes
    Out[13]: NodeView((0, 1, 2, 3, 5, 6, 7, 8, 4))
    

    In particular, the last row/column in your NumPy array corresponds to the node named "4", and the second last row/column is your "8".

    The order of the rows/columns in the output of floyd_warshall_numpy just defaults to that of test.nodes, but you can provide your own by providing an argument for the nodelist parameter:

    In [20]: nx.floyd_warshall_numpy(test, nodelist=range(9))
    Out[20]:
    array([[0., 1., 1., 1., 2., 3., 4., 4., 4.],
           [1., 0., 1., 1., 2., 3., 4., 4., 4.],
           [1., 1., 0., 1., 2., 3., 4., 4., 4.],
           [1., 1., 1., 0., 1., 2., 3., 3., 3.],
           [2., 2., 2., 1., 0., 1., 2., 2., 2.],
           [3., 3., 3., 2., 1., 0., 1., 1., 1.],
           [4., 4., 4., 3., 2., 1., 0., 1., 1.],
           [4., 4., 4., 3., 2., 1., 1., 0., 1.],
           [4., 4., 4., 3., 2., 1., 1., 1., 0.]])