Sub topic 1
Weighted Directed Graphs and Why Negative Weights Matter
This chapter sets up the graph model used in the rest of the tutorial. It also shows, with running code, why Dijkstra's algorithm gives wrong answers once an edge weight drops below zero. Later chapters build Bellman-Ford and Floyd-Warshall to handle that case.
Prerequisites
This chapter assumes you are comfortable with the following:
- Graph basics: vertices, directed edges, adjacency lists and adjacency matrices.
- Big-O notation for time and space.
- Reading and writing basic Python, including lists of tuples and the
heapqmodule. - Dijkstra's algorithm, at least in outline. It helps, but it is not required. The code below includes a full version.
The Model: Weighted Directed Graphs
A weighted directed graph has vertices and directed edges u -> v, and each edge carries a number w(u, v) called its weight. The weight of a path is the sum of its edge weights. A shortest path from s to t is a path with the smallest total weight among all paths from s to t.
This tutorial uses these conventions throughout:
- Vertices are numbered
0ton - 1. - Weights are integers or floats, and they may be negative.
- If no path exists, the distance is
math.inf. - The distance from a vertex to itself starts at
0.
Three representations
The algorithms in this tutorial each read the graph in a different form.
| Representation | Shape | Space | Natural fit |
|---|---|---|---|
| Edge list | `[(u, v, w), ...]` | O(E) | Bellman-Ford, which scans every edge each round |
| Adjacency list | `adj[u] = [(v, w), ...]` | O(V + E) | Dijkstra, which expands one vertex at a time |
| Adjacency matrix | `M[u][v] = w` or `inf` | O(V²) | Floyd-Warshall, which updates every pair |
Converting between them takes only a few lines:
import math
n = 4
edges = [(0, 1, 2), (0, 2, 5), (2, 1, -4), (1, 3, 1)]
# Edge list -> adjacency list
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
# Edge list -> adjacency matrix (keep the cheapest parallel edge)
matrix = [[math.inf] * n for _ in range(n)]
for i in range(n):
matrix[i][i] = 0
for u, v, w in edges:
matrix[u][v] = min(matrix[u][v], w)
print(adj) # [[(1, 2), (2, 5)], [(3, 1)], [(1, -4)], []]
print(matrix) # [[0, 2, 5, inf], [inf, 0, inf, 1], [inf, -4, 0, inf], [inf, inf, inf, 0]]Where Negative Weights Come From
Negative weights show up whenever an edge stands for a gain instead of a cost:
- Costs and rewards together. A delivery route may pay a toll on one road and earn a bonus for a pickup on another.
- Energy. An electric vehicle spends charge going uphill and regains some going downhill.
- Difference constraints. A system of constraints like
x_v - x_u <= cturns into a graph with edgeu -> vof weightc, andcis often negative. Schedulers and layout engines solve these with Bellman-Ford. - Logarithms of ratios. If you multiply rates along a path, taking
-log(rate)turns the product into a sum, and rates above 1 become negative weights. The arbitrage chapter at the end uses this.
Why Dijkstra Breaks
Dijkstra's algorithm takes the unvisited vertex with the smallest tentative distance and declares that distance final. The proof that this is safe assumes that continuing a path can never make it shorter. With non-negative weights that holds: any detour through a not-yet-finalized vertex costs at least as much as that vertex's current distance. A negative edge breaks the assumption. A path that looks expensive at first can pass through a negative edge and end up cheaper than a distance Dijkstra already finalized.
Here is the example graph:
The true shortest path to vertex 1 is 0 -> 2 -> 1 with weight 5 + (-4) = 1, and to vertex 3 it is 0 -> 2 -> 1 -> 3 with weight 2. The code below runs a standard Dijkstra and compares it with a brute-force search over all simple paths:
import heapq
import math
def dijkstra(n, adj, source):
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 # u's distance is declared final here
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
def brute_force(n, adj, source):
# Tries every simple path. Exponential time; for checking small graphs only.
best = [math.inf] * n
def dfs(u, cost, seen):
best[u] = min(best[u], cost)
for v, w in adj[u]:
if v not in seen:
seen.add(v)
dfs(v, cost + w, seen)
seen.remove(v)
dfs(source, 0, {source})
return best
n = 4
edges = [(0, 1, 2), (0, 2, 5), (2, 1, -4), (1, 3, 1)]
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
print(dijkstra(n, adj, 0)) # [0, 2, 5, 3]
print(brute_force(n, adj, 0)) # [0, 1, 5, 2]This is the order of events:
- Dijkstra pops vertex 0 and sets
dist[1] = 2anddist[2] = 5. - It pops vertex 1 at distance 2 and marks it final. It then sets
dist[3] = 3. - It pops vertex 3 and marks it final.
- It pops vertex 2 at distance 5. The edge
2 -> 1would give1, but vertex 1 is already final, so the edge is skipped.
The error also spreads. Vertex 3 is wrong even though no negative edge enters it, because its distance came from the wrong value at vertex 1.
The Tempting Fix That Fails: Shift All Weights
A common first idea is to add a constant c to every edge so that all weights become non-negative, and then run Dijkstra. This changes which path is shortest. A path with k edges gains k * c, so paths with more edges are penalized more.
If you add 4 to every edge in the example, the weights become 0->1: 6, 0->2: 9, 2->1: 0, and 1->3: 5. The direct path 0 -> 1 now costs 6, while 0 -> 2 -> 1 costs 9. Dijkstra correctly finds 6 on the shifted graph, but 6 corresponds to the wrong path in the original graph.
A per-vertex reweighting does preserve shortest paths: w'(u, v) = w(u, v) + h(u) - h(v). Johnson's algorithm, covered later, computes h with Bellman-Ford.
When Shortest Paths Stop Existing
Negative edges can cause a worse problem than wrong answers. If a cycle has negative total weight and you can reach it from the source, you can go around it as many times as you like, and every lap lowers the cost. Any vertex reachable from that cycle then has no shortest path at all. Its distance is effectively -inf. A later chapter treats this in full. For now, keep two facts in mind:
- A negative edge does not imply a negative cycle. The example graph has no cycles at all, and its shortest paths are well defined.
- In an undirected graph, one negative edge
{u, v}is already a negative cycle,u -> v -> u. Treating undirected edges as two directed edges makes this concrete. For this reason, the algorithms in this tutorial are about directed graphs.
| Graph property | Dijkstra correct? | Shortest paths defined? |
|---|---|---|
| All weights ≥ 0 | Yes | Yes |
| Some negative edges, no negative cycles | Not guaranteed | Yes |
| Negative cycle reachable from source | No | No, for vertices reachable from the cycle |
| Undirected with a negative edge | No | No, near that edge |
The rest of the tutorial handles the middle two rows. Bellman-Ford and Floyd-Warshall compute correct distances when shortest paths exist, and they report a negative cycle when shortest paths do not exist.
Exercise
Add the edge (3, 0, -3) to the example graph. Do shortest paths from vertex 0 still exist? Justify your answer using cycle weights.
Show answer
No. The cycle 0 -> 2 -> 1 -> 3 -> 0 has weight 5 - 4 + 1 - 3 = -1, which is negative and reachable from 0. Every vertex on it can be reached with arbitrarily low cost, so no shortest path exists. (The other cycle, 0 -> 1 -> 3 -> 0, has weight 2 + 1 - 3 = 0, which on its own would be harmless.)
Exercise
Build a graph with three vertices and exactly one negative edge on which the "add a constant to every edge" trick gives the correct answer, and explain why it works there.
Show answer
Use edges 0->1 (weight -1) and 1->2 (weight 3). There is only one path from 0 to each vertex, so shifting the weights cannot change which path is shortest. The shifted distances are wrong (each one gains c times the number of edges in its path), but the chosen paths are right. The trick breaks only when competing paths have different edge counts.