Sub topic 1
Weighted Graphs and How to Represent Them
Prerequisites
This chapter assumes you know basic graph terms (vertices, edges, directed and undirected graphs), adjacency lists, Big-O notation, and basic Python. It also assumes you are familiar with breadth-first search (BFS).
Weighted Graphs
A weighted graph gives each edge a number called its weight. The weight can stand for distance, time, or cost. In Python, a dict-based adjacency list stores each weight next to its neighbor:
graph = {
"A": [("B", 4), ("C", 1)],
"C": [("B", 2), ("D", 5)],
"B": [("D", 1)],
"D": [],
}Each key is a vertex. Its value lists (neighbor, weight) pairs for the edges leaving that vertex. For an undirected graph, store every edge in both directions.
The Single-Source Shortest Path Problem
Pick a source vertex s. For every vertex v, find the smallest total weight of any path from s to v. BFS solves this only when all edges cost the same. In the graph above, the direct edge A→B costs 4, but the path A→C→B costs 3. Counting edges gives the wrong answer here, so you have to add up the weights.
Dijkstra's algorithm solves this problem when every weight is non-negative.
Edge Relaxation
The algorithm keeps a tentative distance dist[v] for each vertex. This is the best path cost found so far. It starts at 0 for the source and infinity for every other vertex. Relaxing an edge (u, v, w) checks whether going through u gives a cheaper path to v:
import math
dist = {"A": 0, "B": math.inf, "C": math.inf, "D": math.inf}
def relax(u, v, w):
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return True
return False
relax("A", "B", 4) # dist["B"] becomes 4
relax("A", "C", 1) # dist["C"] becomes 1
relax("C", "B", 2) # dist["B"] improves to 3
print(dist) # {'A': 0, 'B': 3, 'C': 1, 'D': inf}Tentative distances can only go down. They are always upper bounds on the true distance.
The Greedy Rule
Relaxing edges in an arbitrary order can repeat a lot of work. Dijkstra's algorithm fixes the order with one rule: take the unvisited vertex with the smallest tentative distance, mark it as visited (final), and relax its outgoing edges.
This rule depends on non-negative weights. If no weight is negative, no path through a vertex that is farther away can come back and beat the closest one.
Exercise
In the example graph, which vertex does the greedy rule select second, and what is its final distance?
Show answer
C, with distance 1. A is selected first with distance 0. After A's edges are relaxed, C (1) is closer than B (4).