Sub topic 1
Weighted Directed Graphs and Why Negative Weights Matter
A shortest path algorithm is only as good as its assumptions about edge weights. Dijkstra's algorithm assumes that no edge weight is negative. This chapter shows what goes wrong when that assumption fails, which is the reason Bellman-Ford and Floyd-Warshall exist.
Prerequisites
This chapter assumes you know:
- Graph basics: vertices, directed edges, adjacency lists, and adjacency matrices
- Big-O notation
- Basic Python, including lists and tuples
- Dijkstra's algorithm, at least roughly (helpful but not required)
The Working Model
A weighted directed graph has vertices numbered 0..n-1 and edges (u, v, w). Each edge goes from u to v and costs w. The weight of a path is the sum of its edge weights. Throughout the tutorial, a graph is stored as an edge list:
edges = [(0, 1, 1), (0, 2, 4), (2, 1, -5), (1, 3, 1)]A weight can be any real number. Negative weights show up in real models:
| Domain | What a negative weight means |
|---|---|
| Logistics | A leg that pays a rebate or subsidy |
| Finance | `-log(rate)` for a profitable currency exchange |
| Constraint systems | A difference constraint such as `x_v - x_u <= w` |
| Games and planning | An action that restores energy or resources |
Why Dijkstra Breaks
Dijkstra's algorithm marks a vertex as finished the first time it pops that vertex from the priority queue. That step is safe only if no path found later can be cheaper. When every weight is non-negative, extending a path can never lower its cost, so the rule holds. A negative edge can lower the cost, so the rule fails.
import heapq
import math
def dijkstra(n, edges, source):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
dist = [math.inf] * n
dist[source] = 0
done = [False] * n
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if done[u]:
continue
done[u] = True
for v, w in adj[u]:
if not done[v] and d + w < dist[v]:
dist[v] = d + w
heapq.heappush(heap, (dist[v], v))
return dist
edges = [(0, 1, 1), (0, 2, 4), (2, 1, -5), (1, 3, 1)]
print(dijkstra(4, edges, 0)) # [0, 1, 4, 2]The correct answer is [0, -1, 4, 0]. The path 0 → 2 → 1 costs 4 − 5 = −1. Dijkstra had already finished vertex 1 at cost 1, and it had also finished vertex 3 using that wrong value.
Common Errors
- Adding a constant to every weight. Shifting all weights by the same amount penalizes paths with many edges, so the shortest path can change. Johnson's algorithm reweights correctly, and a later chapter covers it.
- Removing the
donecheck. Dijkstra without thedonecheck becomes a label-correcting algorithm. It gives correct results on graphs without negative cycles, but it can take exponential time in the worst case. - Assuming a shortest path always exists. If a cycle has negative total weight, you can go around it forever and keep lowering the cost. The chapter on negative cycles covers this case.
Exercise
In the example graph, change the weight of edge 2 → 1 from -5 to -2. Does Dijkstra now return correct distances? Explain why.
Show answer
No. The true distance to vertex 1 becomes min(1, 4 - 2) = 1, so dist[1] = 1 is still correct, and vertex 3 at cost 2 is also correct. In this case the output happens to be right because the negative edge does not produce a cheaper path. Dijkstra gives no guarantee here, though. Correctness on a graph with negative edges depends on the specific weights, so you cannot rely on it.
Exercise
Why does a single negative edge in an undirected graph make shortest paths undefined?
Show answer
An undirected edge {u, v} with weight w < 0 can be crossed back and forth. The cycle u → v → u has weight 2w < 0, so it is a negative cycle, and you can repeat it to make a path's cost as low as you like.