Negative weights
- Algorithms course
- Advanced
- Lesson 33/56
- 4 min
Bellman-Ford handles negative weights.
Negative weights
Bellman-Ford is a single-source shortest path algorithm that supports negative edge weights. It does what Dijkstra cannot.
The algorithm relaxes all edges n-1 times. This relies on the fact that the longest path has at most n-1 edges.
Edge list
Bellman-Ford works with an edge list rather than a graph object. Each edge is a (u, v, w) triple: from u to v with weight w.
This representation lets the algorithm traverse all edges one by one. Complexity is O(n·m); m is the edge count.
Practice init_edges function
Write init_edges(). Return the edge list. Print it with print(init_edges()).
Starter code
def init_edges():
# Return edge listSample solution
def init_edges():
# Return edge list
return [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1), (2, 3, 5)]
print(init_edges())Expected output
[(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1), (2, 3, 5)]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is Bellman-Ford's advantage over Dijkstra?
- Supports negative weights Correct answer
- Uses less memory
- Runs faster
- Solves all pairs
Explanation: Bellman-Ford supports negative weights.
2 Edge definition
edges = [(0, 1, ____)]
edges = [(0, 1, 4)]
Explanation: 4 is right.
3 Negative weights: match the terms
| Term | Meaning |
|---|---|
(0,1,4) |
0→1 |
(0,2,1) |
0→2 |
(2,1,2) |
2→1 |
(1,3,1) |
1→3 |