Search code examples
pythongraphmatrixdijkstra

Dijkstra's Algorithm from Adjacency Matrix


I have an adjacency matrix of a directed acyclic graph represented by a 2D array:

[[0, 4, 3, 0]
 [0, 0, 0, 1]
 [0, 3, 0, 1]
 [2, 0, 0, 0]]

Is there a Python module or a quick code snippet that can run Dijkstra's Algorithm on this data type? The Python cookbook uses a priority dictionary I believe, but I'd really like to keep it in a 2D array. Any help would be appreciated.


Solution

  • networkx might fit your needs:

    import networkx as nx
    import numpy as np
    A = np.array([[0, 4, 3, 0],
                  [0, 0, 0, 1],
                  [0, 3, 0, 1],
                  [2, 0, 0, 0]])
    G = nx.from_numpy_matrix(A, create_using=nx.DiGraph())
    print(nx.dijkstra_path(G, 0, 1))
    

    See also: networkx.dijkstra_path