Sub topic 1
Weighted Graphs and How to Represent Them
Dijkstra's algorithm runs on a weighted graph. Before you can trace it or implement it, you need to know what the weights mean, how a program stores them, and which storage choices make the algorithm fast or slow. This chapter covers all three. It also points out a few representation bugs that cause wrong answers later even when the algorithm code is correct.
Prerequisites
This chapter assumes you already know:
- Basic graph terminology: vertices, edges, directed and undirected graphs.
- The adjacency list idea for unweighted graphs.
- Big-O notation for time and memory.
- Basic Python: dicts, lists, tuples, loops, and functions.
- Breadth-first search (BFS), which finds shortest paths when every edge counts as one step.
If BFS is familiar, think of this tutorial as answering one question: what changes when the edges no longer cost the same?
What a Weight Is
A weighted graph attaches a number, the weight, to each edge. The weight is the cost of crossing that edge. Common meanings include:
- Road length in kilometres.
- Expected travel time in seconds.
- Network latency between two routers.
- Monetary cost of a flight or a shipment.
The algorithm doesn't care what the units are. It needs only two things: weights along a path can be added, and smaller totals are better. A path's length is the sum of its edge weights, not the number of edges it contains. This is where BFS stops working. A route with three cheap edges can beat a route with one expensive edge.
The rest of the tutorial uses this small directed graph:
BFS would report that D is two edges from A, through either B or C. The cheapest route by weight is A → C → B → D, which costs 1 + 2 + 1 = 4 and uses three edges. The direct-looking routes cost more: A → B → D is 5 and A → C → D is 6.
Directed versus undirected weighted edges
In a directed graph, an edge from u to v with weight w can only be crossed from u to v. In an undirected graph, the same edge can be crossed both ways at the same cost. Programs usually store an undirected edge as two directed edges, one in each direction. If you forget the second one, the algorithm will report vertices as unreachable even though they are reachable.
Some real networks are directed even when they look undirected. One-way streets are an example. So are uphill and downhill travel times, and asymmetric network links. When the costs differ by direction, store two directed edges with different weights.
The non-negativity requirement
Dijkstra's algorithm requires every weight to be zero or positive. Zero-weight edges are allowed. Negative weights are not, and a graph with negative weights doesn't make Dijkstra fail with an error. It returns wrong distances without any warning. A later chapter explains the mechanism and the alternative, Bellman-Ford. For now, the practical point is to check weights when you build the graph. Building the graph is the cheapest place to catch the problem.
Adjacency Lists with Weights
For unweighted graphs, an adjacency list maps each vertex to its neighbors. For weighted graphs, each neighbor entry becomes a pair: (neighbor, weight). In Python, the usual form is a dict from vertex to a list of tuples. Every implementation in this tutorial uses that format.
Graph data often arrives as an edge list, one (u, v, w) triple per edge, from a file, a database, or an API. This function converts an edge list into the adjacency format and checks the input as it goes:
def build_graph(edges, directed=True):
"""edges: iterable of (u, v, w) triples. Returns dict node -> list of (neighbor, weight)."""
graph = {}
for u, v, w in edges:
if w < 0:
raise ValueError(f"negative weight {w} on edge {u}->{v}")
graph.setdefault(u, []).append((v, w))
graph.setdefault(v, []) # make sure sink vertices appear as keys
if not directed:
graph[v].append((u, w))
return graph
edges = [
("A", "B", 4),
("A", "C", 1),
("C", "B", 2),
("C", "D", 5),
("B", "D", 1),
]
directed = build_graph(edges)
print(directed)
# {'A': [('B', 4), ('C', 1)], 'B': [('D', 1)], 'C': [('B', 2), ('D', 5)], 'D': []}
undirected = build_graph(edges, directed=False)
print(undirected["D"])
# [('C', 5), ('B', 1)]There are three details in this code to notice.
graph.setdefault(v, [])registers vertices that have no outgoing edges. Without it,Dwould not be a key at all. Code that listsgraph.keys()to find every vertex would then miss it.- The weight check runs once per edge at build time, so a bad input fails loudly and close to its source.
- The undirected case appends the reverse edge with the same weight. Each undirected edge therefore produces two list entries.
Parallel edges and self-loops
Real data is messy, so two cases come up often:
- Parallel edges: two edges from u to v with different weights, such as two flights on the same route at different prices. An adjacency list can hold both. Dijkstra handles them correctly because it considers each one and keeps the cheaper result. If memory matters, you can collapse them to the minimum weight when you build the graph.
- Self-loops: an edge from u to itself. With a non-negative weight, a self-loop can never shorten a path, so it is harmless and only costs a little time. You can drop self-loops at build time.
Adjacency Matrices
An adjacency matrix stores a V × V table where entry [i][j] holds the weight of the edge from vertex i to vertex j. For weighted graphs, a missing edge cannot be stored as 0, because 0 is a valid weight. Use infinity instead:
import math
def to_matrix(graph):
nodes = sorted(graph)
index = {node: i for i, node in enumerate(nodes)}
n = len(nodes)
matrix = [[math.inf] * n for _ in range(n)]
for i in range(n):
matrix[i][i] = 0
for u, neighbors in graph.items():
for v, w in neighbors:
i, j = index[u], index[v]
matrix[i][j] = min(matrix[i][j], w) # keep the cheapest parallel edge
return nodes, matrix
graph = {
"A": [("B", 4), ("C", 1)],
"B": [("D", 1)],
"C": [("B", 2), ("D", 5)],
"D": [],
}
nodes, matrix = to_matrix(graph)
print(nodes)
for row in matrix:
print(row)
# ['A', 'B', 'C', 'D']
# [0, 4, 1, inf]
# [inf, 0, inf, 1]
# [inf, 2, 0, 5]
# [inf, inf, inf, 0]A matrix stores one weight per cell, so parallel edges have to be merged. The min call keeps the cheapest one, which is the right choice for shortest paths.
Choosing a Representation
Dijkstra's main loop does one thing over and over: for a chosen vertex, it walks through all of that vertex's outgoing edges. The representation you pick decides how much that walk costs.
| Operation or property | Adjacency list | Adjacency matrix |
|---|---|---|
| Memory | O(V + E) | O(V²) |
| Iterate over neighbors of u | O(deg(u)) | O(V) |
| Check whether edge u→v exists | O(deg(u)) | O(1) |
| Add a vertex | O(1) | O(V²) to rebuild, or O(V) amortised with resizing |
| Holds parallel edges | Yes | No, one value per cell |
| Good fit | Sparse graphs: roads, networks, most real data | Dense graphs, small V, constant-time edge checks |
Across a full run, Dijkstra visits each vertex's neighbors once. With adjacency lists, that adds up to O(V + E) neighbor work. With a matrix it adds up to O(V²) no matter how few edges exist. Most practical graphs are sparse, meaning E is close to V rather than V². A road network has millions of intersections, and each one connects to only a handful of roads. A matrix for 10⁶ vertices would need 10¹² cells, which no ordinary machine can hold. An adjacency list for the same graph fits in a few hundred megabytes.
A matrix is still a reasonable choice when the graph is small or dense. One example is a complete graph of 500 cities where every pair has a distance. In that case E is close to V² anyway, and the matrix's simple indexing can be faster in practice.
Vertex labels
The examples use string labels such as "A", which keeps them easy to read. Production code often maps labels to integers 0..V−1 and stores the adjacency list as a list of lists. That uses less memory and runs faster in Python than dict lookups. The algorithm doesn't change. Only the container type changes.
Common Representation Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting the reverse edge in an undirected graph | Vertices reported unreachable | Append both directions at build time |
| Sink vertices missing as keys | `KeyError`, or vertex count too low | `setdefault(v, [])` for every endpoint |
| 0 used for "no edge" in a matrix | Shortest paths that use edges that don't exist | Use `math.inf` |
| Negative weights accepted silently | Wrong distances with no error | Validate `w >= 0` during construction |
| Weights stored as strings from a CSV | `TypeError`, or string concatenation instead of addition | Convert with `int()` or `float()` while parsing |
Exercise
An undirected graph has 7 vertices and 10 edges. If you build it with build_graph(edges, directed=False), how many (neighbor, weight) tuples appear across all adjacency lists, and how many keys does the dict have if every vertex touches at least one edge?
Show answer
Each undirected edge is stored once in each direction, so there are 2 × 10 = 20 tuples. The dict has 7 keys, one per vertex.
Exercise
Someone removes the line graph.setdefault(v, []) from build_graph and builds the directed example graph. Which vertex disappears from the keys, and why might code that only reads graph.get(u, []) still work?
Show answer
D disappears, because it has no outgoing edges and is never the u in any triple. Code that reads neighbors with graph.get(u, []) gets an empty list for D instead of raising KeyError, so neighbor traversal still works. Code that counts or lists vertices from graph.keys() will miss D.
Exercise
You need shortest paths on a road network with 2,000,000 intersections and about 5,000,000 road segments. Estimate the number of cells an adjacency matrix would need, and say which representation you would use.
Show answer
A matrix needs V² = 4 × 10¹² cells, far more than any ordinary machine's memory. An adjacency list stores O(V + E), about 7 million entries (roughly 12 million tuples if roads are two-way), so use an adjacency list.
Exercise
A CSV row reads "A,B,7". Your parser stores the weight without converting it. What goes wrong when the algorithm adds two such weights, such as "7" and "3"?
Show answer
Python concatenates the strings into "73" instead of adding them to get 10. Mixing a string with an integer, such as 0 + "7", raises a TypeError. Convert weights with int() or float() while parsing.