Sub topic 15
Computing shortest paths with Dijkstra's algorithm
This chapter assumes you know weighted graphs and shortest paths. It also assumes you know how a link-state database is built by flooding. Once flooding has given every router the same database, each router runs Dijkstra's algorithm on its own. This step is called shortest path first (SPF).
What SPF produces
The database describes a graph. The router puts itself at the root and computes the lowest-cost path to every other node. The result is a shortest-path tree. The router does not store whole paths. It keeps only the first hop toward each destination, because that is what the forwarding table needs.
The algorithm
- Set the distance to the root to 0. Treat every other node as unreached.
- Pick the unfinished node with the smallest known distance. Mark it done.
- For each neighbor of that node, compute distance plus link cost. If this is lower than the neighbor's known distance, record it and remember the first hop.
- Repeat until every reachable node is done.
The first hop of a neighbor of the root is the neighbor itself. Any node farther away inherits the first hop of the node it was reached through.
import heapq
def spf(graph, source):
"""graph: node -> {neighbor: cost}. Returns (distance, first_hop) per destination."""
dist = {source: 0}
first_hop = {}
done = set()
heap = [(0, source, None)]
while heap:
d, node, hop = heapq.heappop(heap)
if node in done:
continue
done.add(node)
if node != source:
first_hop[node] = hop
for nbr, cost in graph[node].items():
nd = d + cost
if nbr not in done and nd < dist.get(nbr, float("inf")):
dist[nbr] = nd
heapq.heappush(heap, (nd, nbr, nbr if node == source else hop))
return dist, first_hop
graph = {
"A": {"B": 1, "C": 4},
"B": {"A": 1, "C": 2, "D": 5},
"C": {"A": 4, "B": 2, "D": 1},
"D": {"B": 5, "C": 1},
}
print(spf(graph, "A"))The heap holds candidate entries. A may be pushed more than once when a cheaper path appears, so the done check discards stale entries.
Worked example
A first reaches B at cost 1 and C at cost 4. Then B is finished, and the path A-B-C costs 3, which beats 4. D is first seen through B at cost 6. After C is finished, A-B-C-D costs 4, which beats 6. The output is:
| Destination | Cost | First hop |
|---|---|---|
| B | 1 | B |
| C | 3 | B |
| D | 4 | B |
A's forwarding table sends all three destinations out toward B, even though the direct A-C link exists.
Common errors
- Negative costs. Dijkstra assumes finishing a node fixes its distance, and a negative link breaks that. Link-state metrics are positive for this reason.
- Different databases. If two routers hold different databases, they compute inconsistent trees and can create forwarding loops. This is why flooding must be reliable.
- Forgetting first hops. Distances alone are not a forwarding table. You must track which neighbor each path starts with.
- Ties. Equal-cost paths are common. OSPF can install several next hops (equal-cost multipath), but code that keeps only one will hide the others.
In OSPF, a topology change triggers a new SPF run. This costs CPU on large areas, which is one reason areas exist.
Exercise
Using the graph above, run SPF from D. What are the cost and first hop to A?
Show answer
D reaches C at cost 1 and B at cost 5. Through C, B costs 1+2=3, which beats 5. A costs 4 through C-B-A (1+2+1), and the direct route via C costs 1+4=5. The cost to A is 4 and the first hop is C.