Sub topic 1
Weighted Graphs and How to Represent Them
Dijkstra's algorithm works on graphs where every edge has a number attached to it. This chapter shows what that number means, how to store it in Python, and which storage choice fits the rest of this tutorial.
Prerequisites
This chapter assumes you already know:
- Basic graph terminology: vertices, edges, and directed versus undirected graphs
- The adjacency list representation of an unweighted graph
- Big-O notation
- Basic Python: dicts, lists, tuples, loops, and functions
- Breadth-first search (BFS), which finds shortest paths when every edge counts as one step
What a Weight Means
A weighted graph is a graph where each edge carries a numeric weight. The weight is the cost of moving along that edge. Depending on the problem, it can stand for distance in kilometres, travel time, network latency, or money.
The weight of a path is the sum of the weights of its edges. That is the key difference from BFS. BFS counts edges, so a path with fewer edges always wins. With weights, a route through more edges can be cheaper than a direct one.
In this graph the direct edge from A to B costs 4. The route A → C → B costs 1 + 2 = 3, which is cheaper even though it uses two edges.
Storing Weights in an Adjacency List
An unweighted adjacency list maps each vertex to a list of neighbours. For a weighted graph, each neighbour becomes a (neighbor, weight) tuple. Every implementation in this tutorial uses this format.
def build_graph(edges, directed=True):
"""edges: iterable of (u, v, weight) tuples."""
graph = {}
for u, v, w in edges:
graph.setdefault(u, []).append((v, w))
graph.setdefault(v, []) # make sure sink vertices appear as keys
if not directed:
graph[v].append((u, w)) # undirected: store the edge both ways
return graph
edges = [("A", "B", 4), ("A", "C", 1), ("C", "B", 2), ("C", "D", 5), ("B", "D", 1)]
graph = build_graph(edges)
print(graph)
# {'A': [('B', 4), ('C', 1)], 'B': [('D', 1)], 'C': [('B', 2), ('D', 5)], 'D': []}Adjacency List Versus Adjacency Matrix
An adjacency matrix a V × V table in which cell [u][v] holds the weight of edge u → v, or infinity if the edge does not exist.
| Property | Adjacency list | Adjacency matrix |
|---|---|---|
| Memory | O(V + E) | O(V²) |
| Iterate neighbours of u | O(degree of u) | O(V) |
| Check whether edge u → v exists | O(degree of u) | O(1) |
| Best for | Sparse graphs (road maps, networks) | Dense graphs, small V |
Most real graphs are sparse: each vertex connects to only a few others. Dijkstra's algorithm spends its time scanning the neighbours of each vertex, so the adjacency list is the usual choice.
Common Errors
- Forgetting the reverse edge. In an undirected graph, a road between A and B must appear in both
graph["A"]andgraph["B"]. If you store it only once, some paths disappear. - Missing keys for vertices with no outgoing edges. If
Dnever appears as a key,graph["D"]raisesKeyError. Either add empty lists, asbuild_graphdoes, or read neighbours withgraph.get(u, []). - Parallel edges. Two edges from u to v with different weights are both kept in a list. That is harmless, because a shortest-path algorithm will use the cheaper one. A dict-of-dicts layout would silently overwrite one of them.
- Using 0 for "no edge" in a matrix. Zero is a valid weight. Use
float("inf")for an absent edge.
Exercise
Call build_graph with the same five edges but directed=False. How many tuples does graph["B"] contain, and what are they?
Show answer
Three tuples: ('A', 4) from the reversed A–B edge, ('C', 2) from the reversed C–B edge, and ('D', 1) from the B–D edge. In order of insertion: [('A', 4), ('C', 2), ('D', 1)].
Exercise
In the diagram's graph, list every path from A to D and its weight. Which is cheapest?
Show answer
A→B→D = 5, A→C→D = 6, A→C→B→D = 4. The cheapest is A→C→B→D with weight 4, even though it has the most edges.