Sub topic 16
Dijkstra's Algorithm and Why It Fails with Negative Edges
Assume you know weighted graphs, priority queues, and asymptotic notation. This chapter uses relaxation, the operation of improving a known distance when a shorter route is found.
Dijkstra's algorithm
Dijkstra's algorithm finds shortest paths from one source vertex when every edge weight is non-negative. It maintains:
dist[v]: the best distance currently known from the source tov.- A min-priority queue containing candidate vertices.
- A settled set of vertices whose shortest distance is final.
At each step, the algorithm removes the unsettled vertex with the smallest tentative distance. It then relaxes every outgoing edge (u, v) with weight w:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + wWith a binary heap and an adjacency list, the time complexity is O((V + E) log V).
import heapq
def dijkstra(graph, source):
distance = {vertex: float("inf") for vertex in graph}
distance[source] = 0
heap = [(0, source)]
while heap:
current_distance, u = heapq.heappop(heap)
if current_distance != distance[u]:
continue
for v, weight in graph[u]:
new_distance = current_distance + weight
if new_distance < distance[v]:
distance[v] = new_distance
heapq.heappush(heap, (new_distance, v))
return distance
graph = {
"A": [("B", 1), ("C", 4)],
"B": [("C", 2), ("D", 6)],
"C": [("D", 3)],
"D": [],
}
print(dijkstra(graph, "A"))The key correctness idea is that a non-negative edge cannot later create a route than the smallest unsettled distance already selected.
The negative-edge failure
Consider the edges S → A with weight 2, S → B with weight 5, and B → A with weight -10.
Dijkstra settles A first because its tentative distance is 2. It may report 2 as final. However, the route S → B → A costs 5 - 10 = -5. The earlier decision was unsafe.
Bellman-Ford and negative cycle detection
Bellman-Ford also starts with dist[source] = 0 and all other distances set to infinity. It relaxes every edge repeatedly. After V - 1 complete passes, every shortest simple path has been considered because a simple path contains at most V - 1 edges.
A final extra pass checks for an edge that can still be relaxed. If one exists, a negative-weight cycle is reachable from the source. Such a cycle lets a path become cheaper indefinitely, so no finite shortest distance exists.
Bellman-Ford handles negative edges and runs in O(VE) time. It can also report whether a reachable negative cycle exists.
| Algorithm | Negative edges | Negative-cycle detection | Time |
|---|---|---|---|
| Dijkstra | No | No | `O((V + E) log V)` |
| Bellman-Ford | Yes | Yes | `O(VE)` |
Exercise
Why does Bellman-Ford use V - 1 ordinary passes and one additional pass?
Show answer
A shortest simple path uses at most V - 1 edges, so V - 1 passes propagate every such path. If another pass improves a distance, a reachable negative cycle must exist.