Sub topic 1
Weighted Directed Graphs and Why Negative Weights Matter
Prerequisites
This chapter assumes you know vertices, directed edges, and adjacency lists, can read Big-O notation, and can read basic Python. Some familiarity with Dijkstra's algorithm helps but is not required.
Weighted Directed Graphs
A weighted directed graph gives every edge u → v a number w, its weight. The weight can stand for distance, cost, or time. Some problems also need negative weights, such as a rebate, an energy gain, or a log-transformed exchange rate.
Negative weights break Dijkstra's algorithm. Dijkstra marks a vertex as final as soon as it is the closest unvisited vertex. A negative edge found later can still make that vertex cheaper to reach. Take the edges 0→1 (2), 0→2 (5) and 2→1 (-4). Dijkstra finalizes vertex 1 at distance 2, but the real shortest distance is 1, along the path 0→2→1.
Single-Source vs. All-Pairs
| Problem | Question | Algorithm in this tutorial |
|---|---|---|
| Single-source | Shortest distance from one source to every vertex | Bellman-Ford |
| All-pairs | Shortest distance between every pair of vertices | Floyd-Warshall |
Edge Relaxation
Relaxing an edge (u, v, w) means checking whether going through u gives a shorter route to v:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = uThe dist array always holds upper bounds on the true distances. Relaxation can only lower those bounds, and it never pushes one below the true value.
Negative Cycles
A negative cycle is a cycle whose edge weights add up to less than zero. If a path can reach such a cycle, it can go around the cycle again and again, and its cost drops each time. The shortest path to any vertex reachable from that cycle is then undefined, and a correct algorithm must report the cycle instead of returning a number.
The Bellman-Ford Algorithm
Bellman-Ford relaxes every edge V-1 times, where V is the number of vertices. That number of rounds is enough because a shortest path with no cycles uses at most V-1 edges. After those rounds, the algorithm makes one extra pass over all edges. If any edge can still be relaxed, a negative cycle is reachable from the source. The running time is O(VE), where E is the number of edges.
import math
def bellman_ford(n, edges, source):
dist = [math.inf] * n
pred = [None] * n
dist[source] = 0
for _ in range(n - 1):
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
changed = True
if not changed:
break
for u, v, w in edges:
if dist[u] + w < dist[v]:
raise ValueError('negative cycle reachable from source')
return dist, pred
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
dist, pred = bellman_ford(4, edges, 0)
print(dist) # [0, 4, 1, 5]Exercise
What does bellman_ford(3, [(0, 1, 1), (1, 2, -1), (2, 1, -1)], 0) do, and why?
Show answer
It raises ValueError. The cycle 1→2→1 has total weight -2 and can be reached from vertex 0, so an edge can still be relaxed during the extra pass.