Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 753
Hoopdady Avatar asked Apr 30 '26 16:04

Hoopdady


1 Answers

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

like image 57
unutbu Avatar answered May 03 '26 07:05

unutbu