🚀 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.bellman_ford()

AI & DATA SCIENCE // csgraph-bellman-ford

scipy.sparse.csgraph.bellman_ford() computes shortest path distances in a weighted graph, correctly handling negative edge weights and explicitly detecting negative cycles, at the cost of being slower than Dijkstra's algorithm.

Syntax

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

Deep Dive Course

Unlike dijkstra(), which requires non-negative weights, bellman_ford() correctly computes shortest paths even when some edges have negative weight, by repeatedly relaxing, attempting to improve, every edge's distance estimate across multiple passes rather than greedily finalizing distances early. If the graph contains a negative cycle, a loop whose total edge weight sums to a negative number, bellman_ford() detects this and raises an error, since a shortest path isn't a well-defined, finite concept when you could keep looping around a negative cycle to make a path's total distance arbitrarily small.

1Understanding csgraph.bellman_ford()

Unlike dijkstra(), which requires non-negative weights, bellman_ford() correctly computes shortest paths even when some edges have negative weight, by repeatedly relaxing, attempting to improve, every edge's distance estimate across multiple passes rather than greedily finalizing distances early. If the graph contains a negative cycle, a loop whose total edge weight sums to a negative number, bellman_ford() detects this and raises an error, since a shortest path isn't a well-defined, finite concept when you could keep looping around a negative cycle to make a path's total distance arbitrarily small.

💡

Use bellman_ford() specifically when a graph might have negative edge weights but you still need correct, reliable shortest paths, or when you specifically need to detect whether a negative cycle exists at all — dijkstra() is faster but gives wrong answers on negative weights, without any warning.

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

graph = csr_matrix([[0, 1, 0], [0, 0, -1], [0, 0, 0]])
distances = bellman_ford(graph, indices=0)
print(distances)
localhost:3000

2Practical Example

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

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

graph = csr_matrix([[0, 1, 0], [0, 0, -3], [-1, 0, 0]])
try:
    bellman_ford(graph, indices=0)
except Exception as e:
    print("Error:", e)
localhost:3000

3Best Practices

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

1. Use bellman_ford() instead of dijkstra() specifically when negative edge weights are a realistic possibility in your graph

2. Catch and handle the negative-cycle error explicitly, rather than assuming it will never occur, if your graph's weights come from an untrusted or computed source

3. Prefer dijkstra() when you know all weights are non-negative, since it's typically faster for that common case

⚠️

Tip: Use bellman_ford() specifically when a graph might have negative edge weights but you still need correct, reliable shortest paths, or when you specifically need to detect whether a negative cycle exists at all — dijkstra() is faster but gives wrong answers on negative weights, without any warning.

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

graph = csr_matrix([[0, 1, 0], [0, 0, -1], [0, 0, 0]])
distances = bellman_ford(graph, indices=0)
print(distances)
localhost:3000

Examples

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

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

graph = csr_matrix([[0, 1, 0], [0, 0, -3], [-1, 0, 0]])
try:
    bellman_ford(graph, indices=0)
except Exception as e:
    print("Error:", e)

Best Practices

  • Use bellman_ford() instead of dijkstra() specifically when negative edge weights are a realistic possibility in your graph
  • Catch and handle the negative-cycle error explicitly, rather than assuming it will never occur, if your graph's weights come from an untrusted or computed source
  • Prefer dijkstra() when you know all weights are non-negative, since it's typically faster for that common case

Interview Question

Why is a 'shortest path' fundamentally undefined for a pair of nodes connected through a graph containing a negative cycle?

Hint: Think about what happens if you keep looping around a cycle whose total edge weight is negative.

If a cycle's total edge weight sums to a negative number, then a path that loops around that cycle once, and then continues to its actual destination, has a smaller total distance than not looping at all — and looping around it a second time makes the total distance even smaller still. Since there's no limit to how many times you could traverse that cycle, the shortest possible distance for any path that can reach and pass through that cycle keeps decreasing without bound, meaning no finite minimum distance actually exists, which is exactly why algorithms like bellman_ford() detect this situation and raise an error rather than returning a misleading finite number.

Exercises

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

graph = csr_matrix([[0, 1, 0], [0, 0, -1], [0, 0, 0]])
distances = bellman_ford(graph, indices=0)
print(distances)

Frequently Asked Questions

Why is a 'shortest path' fundamentally undefined for a pair of nodes connected through a graph containing a negative cycle?

If a cycle's total edge weight sums to a negative number, then a path that loops around that cycle once, and then continues to its actual destination, has a smaller total distance than not looping at all — and looping around it a second time makes the total distance even smaller still. Since there's no limit to how many times you could traverse that cycle, the shortest possible distance for any path that can reach and pass through that cycle keeps decreasing without bound, meaning no finite minimum distance actually exists, which is exactly why algorithms like bellman_ford() detect this situation and raise an error rather than returning a misleading finite number.

Related Functions

csgraph-dijkstracsgraph-floyd-warshallsparse-csr-matrix