Curriculum
Course: SCIPY
Login
Text lesson

Dijkstra

The dijkstra method finds the shortest path in a graph between elements and accepts the following arguments:

  1. return_predecessors: Boolean; set to True to return the full traversal path, or False otherwise.
  2. indices: Index of the element to compute paths from that specific element only.
  3. limit: Maximum weight of the path.

Example

Determine the shortest path between element 1 and element 2.

import numpy as np
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix

arr = np.array([
  [012],
  [100],
  [200]
])

newarr = csr_matrix(arr)

print(dijkstra(newarr, return_predecessors=True, indices=0))

Floyd Warshall

Use the floyd_warshall() method to compute the shortest paths between all pairs of elements.

Example

Determine the shortest paths between all pairs of elements.

import numpy as np
from scipy.sparse.csgraph import floyd_warshall
from scipy.sparse import csr_matrix

arr = np.array([
  [012],
  [100],
  [200]
])

newarr = csr_matrix(arr)

print(floyd_warshall(newarr, return_predecessors=True))