Search code examples
python-3.xnetworkxshortest-pathdijkstraadjacency-matrix

Using dijkstra_path function in networkx library


I'm using networkx library to find shortest path between two nodes using dijkstra algo as follows

import networkx as nx

A = [[0, 100, 0, 0 , 40, 0],
     [100, 0, 20, 0, 0, 70],
     [0, 20, 0, 80, 50, 0],
     [0, 0, 80, 0, 0, 30],
     [40, 0, 50, 0, 0, 60],
     [0, 70, 0, 30, 60, 0]];

print(nx.dijkstra_path(A, 0, 4))

In the above code I'm using matrix directly, But library requires graph to be created as follows

G = nx.Graph()
G = nx.add_node(<node>)
G.add_edge(<node 1>, <node 2>)

It is very time consuming to create matrix by using above commands. Is there any way to give input as weighted matrix to the dijkstra_path function.


Solution

  • First you need to convert your adjacency matrix to a numpy matrix with np.array. Then you can simply create your graph with from_numpy_matrix.

    import networkx as nx
    import numpy as np
    
    A = [[0, 100, 0, 0 , 40, 0],
         [100, 0, 20, 0, 0, 70],
         [0, 20, 0, 80, 50, 0],
         [0, 0, 80, 0, 0, 30],
         [40, 0, 50, 0, 0, 60],
         [0, 70, 0, 30, 60, 0]]
    
    a = np.array(A)
    G = nx.from_numpy_matrix(a)
    
    print(nx.dijkstra_path(G, 0, 4))
    

    Output:

    [0, 4]
    

    Side note: you can check the graph edges with the following code.

    for edge in G.edges(data=True):
        print(edge)
    

    Output:

    (0, 1, {'weight': 100})
    (0, 4, {'weight': 40})
    (1, 2, {'weight': 20})
    (1, 5, {'weight': 70})
    (2, 3, {'weight': 80})
    (2, 4, {'weight': 50})
    (3, 5, {'weight': 30})
    (4, 5, {'weight': 60})