🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEscipy

scipy Documentation

LOADING ENGINE...

csgraph.dijkstra()

AI & DATA SCIENCE // csgraph-dijkstra

scipy.sparse.csgraph.dijkstra() computes the shortest path distances between nodes in a weighted graph using Dijkstra's algorithm, requiring all edge weights to be non-negative.

Syntax

scipy.sparse.csgraph.dijkstra(csgraph, directed=True, indices=None)

Deep Dive Course

dijkstra() takes a graph as a sparse adjacency matrix, where the matrix's stored values represent edge weights/distances, and computes the shortest-path distance from a source node, or every node if indices is omitted, to every other reachable node, returning inf for any node that can't be reached at all. Dijkstra's algorithm specifically requires all edge weights to be non-negative — a negative edge weight can produce incorrect results, since the algorithm's greedy strategy of always expanding the currently-closest node assumes distances can only increase as you explore further, an assumption negative weights violate.

1Understanding csgraph.dijkstra()

dijkstra() takes a graph as a sparse adjacency matrix, where the matrix's stored values represent edge weights/distances, and computes the shortest-path distance from a source node, or every node if indices is omitted, to every other reachable node, returning inf for any node that can't be reached at all. Dijkstra's algorithm specifically requires all edge weights to be non-negative — a negative edge weight can produce incorrect results, since the algorithm's greedy strategy of always expanding the currently-closest node assumes distances can only increase as you explore further, an assumption negative weights violate.

💡

Dijkstra's algorithm requires non-negative edge weights — if your graph might have negative weights, but no negative cycles, use bellman_ford() instead, which correctly handles that case at the cost of being somewhat slower.

editor.html
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

graph = csr_matrix([[0, 1, 5], [0, 0, 2], [0, 0, 0]])
distances = dijkstra(graph, indices=0)
print(distances)
localhost:3000

2Practical Example

Here is a real-world application of csgraph.dijkstra() showing how it is used in production SciPy code.

editor.html
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

graph = csr_matrix([[0, 1, 5], [0, 0, 2], [0, 0, 0]])
distances, predecessors = dijkstra(graph, indices=0, return_predecessors=True)
print(predecessors)
localhost:3000

3Best Practices

Follow these guidelines when working with csgraph.dijkstra():

1. Use dijkstra() specifically for graphs with non-negative edge weights, where it's typically faster than more general alternatives

2. Pass indices to compute shortest paths from only specific source nodes, instead of computing the full all-pairs result when you only need a few sources

3. Check for inf values in the result to identify nodes that aren't reachable from a given source, rather than assuming every node is always reachable

⚠️

Tip: Dijkstra's algorithm requires non-negative edge weights — if your graph might have negative weights, but no negative cycles, use bellman_ford() instead, which correctly handles that case at the cost of being somewhat slower.

editor.html
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

graph = csr_matrix([[0, 1, 5], [0, 0, 2], [0, 0, 0]])
distances = dijkstra(graph, indices=0)
print(distances)
localhost:3000

Examples

Example 01Basic Usage
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

graph = csr_matrix([[0, 1, 5], [0, 0, 2], [0, 0, 0]])
distances = dijkstra(graph, indices=0)
print(distances)
Example 02Advanced Example
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

graph = csr_matrix([[0, 1, 5], [0, 0, 2], [0, 0, 0]])
distances, predecessors = dijkstra(graph, indices=0, return_predecessors=True)
print(predecessors)

Best Practices

  • Use dijkstra() specifically for graphs with non-negative edge weights, where it's typically faster than more general alternatives
  • Pass indices to compute shortest paths from only specific source nodes, instead of computing the full all-pairs result when you only need a few sources
  • Check for inf values in the result to identify nodes that aren't reachable from a given source, rather than assuming every node is always reachable

Interview Question

Why can Dijkstra's algorithm produce incorrect results if a graph has a negative edge weight?

Hint: Think about the core greedy assumption the algorithm relies on at every step.

Dijkstra's algorithm greedily finalizes the shortest known distance to whichever unvisited node currently has the smallest tentative distance, assuming that no shorter path to that node could possibly be discovered later through a node that hasn't been visited yet, since visiting more nodes can only add more distance. A negative edge weight breaks that assumption directly: a path routed through a node with a seemingly larger current distance could still end up shorter overall if it later crosses a negative-weight edge, but Dijkstra's algorithm has already locked in and moved past that node's distance as final by the time it would discover that shortcut, producing an incorrect, too-large result.

Exercises

MediumPractice using csgraph.dijkstra() in a real scenario.
View Solution
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

graph = csr_matrix([[0, 1, 5], [0, 0, 2], [0, 0, 0]])
distances = dijkstra(graph, indices=0)
print(distances)

Frequently Asked Questions

Why can Dijkstra's algorithm produce incorrect results if a graph has a negative edge weight?

Dijkstra's algorithm greedily finalizes the shortest known distance to whichever unvisited node currently has the smallest tentative distance, assuming that no shorter path to that node could possibly be discovered later through a node that hasn't been visited yet, since visiting more nodes can only add more distance. A negative edge weight breaks that assumption directly: a path routed through a node with a seemingly larger current distance could still end up shorter overall if it later crosses a negative-weight edge, but Dijkstra's algorithm has already locked in and moved past that node's distance as final by the time it would discover that shortcut, producing an incorrect, too-large result.

Related Functions

csgraph-bellman-fordcsgraph-floyd-warshallsparse-csr-matrix