Edexcel International Advanced Level Computer Science, point 18.2.6
A graph (14.1.3) is made of vertices and edges. In Unit 4 you must be able to select, amend and write code to represent one, with an adjacency matrix or an adjacency list. Check the PLS for details.
The example graph (undirected, weighted): edges A-B (4), A-C (2), B-D (5), C-D (8).
a. Adjacency matrix
A 2D list, where matrix[i][j] holds the weight of the edge from vertex i to vertex j, or 0 (or infinity) if there is none.
vertices = ["A", "B", "C", "D"]
# vertex name -> row/column
index = {v: i for i, v in enumerate(vertices)}
n = len(vertices)
matrix = [[0] * n for _ in range(n)]
def add_edge_matrix(a, b, weight):
matrix[index[a]][index[b]] = weight
# undirected: both ways
matrix[index[b]][index[a]] = weight
add_edge_matrix("A", "B", 4)
add_edge_matrix("A", "C", 2)
add_edge_matrix("B", "D", 5)
add_edge_matrix("C", "D", 8)
for row in matrix:
print(row)
A B C D
A [ 0, 4, 2, 0 ]
B [ 4, 0, 0, 5 ]
C [ 2, 0, 0, 8 ]
D [ 0, 5, 8, 0 ]
Operations:
def has_edge_matrix(a, b):
return matrix[index[a]][index[b]] != 0
def neighbours_matrix(a):
row = matrix[index[a]]
return [vertices[j] for j in range(n) if row[j] != 0]
# True False
print(has_edge_matrix("A", "B"), has_edge_matrix("A", "D"))
# ['B', 'C']
print(neighbours_matrix("D"))
- An undirected graph's matrix is symmetrical.
- For a directed graph, set only
matrix[a][b](the direction of the edge). - Use
1for an unweighted graph. - Use
float("inf")for "no edge" if 0 could be a real weight.
Benefits: checking an edge is , simple. Drawbacks: uses memory (wasteful when few edges), and finding neighbours takes .
b. Adjacency list
A dictionary where each key is a vertex and each value is a list of the vertices it connects to (with weights).
graph = {v: [] for v in ["A", "B", "C", "D"]}
def add_edge_list(a, b, weight):
graph[a].append((b, weight))
# undirected: both ways
graph[b].append((a, weight))
add_edge_list("A", "B", 4)
add_edge_list("A", "C", 2)
add_edge_list("B", "D", 5)
add_edge_list("C", "D", 8)
for vertex, edges in graph.items():
print(vertex, edges)
A: [(B, 4), (C, 2)]
B: [(A, 4), (D, 5)]
C: [(A, 2), (D, 8)]
D: [(B, 5), (C, 8)]
Operations:
def has_edge_list(a, b):
return any(v == b for v, w in graph[a])
def weight_of(a, b):
for v, w in graph[a]:
if v == b:
return w
return None
def neighbours_list(a):
return [v for v, w in graph[a]]
print(has_edge_list("A", "C"), weight_of("B", "D")) # True 5
print(neighbours_list("D")) # ['B', 'C']
Directed graph: add only graph[a].append((b, w)).
An alternative using nested dictionaries (graph[a][b] = weight) gives fast weight look-up and is used in Dijkstra's algorithm (21.2.1):
graph2 = {"A": {"B": 4, "C": 2}, "B": {"A": 4, "D": 5},
"C": {"A": 2, "D": 8}, "D": {"B": 5, "C": 8}}
print(graph2["A"]["C"]) # 2
Benefits: memory is , neighbours found quickly, good for sparse graphs. Drawbacks: checking one edge means scanning a list.
Comparison
| Adjacency matrix | Adjacency list | |
|---|---|---|
| Memory | ||
| Check an edge | ||
| List neighbours | Quick | |
| Add an edge | ||
| Add a vertex | Needs a new row and column | Add a key |
| Best for | Dense graphs, quick edge checks | Sparse graphs, traversals |
Using the representation: a traversal
from collections import deque
def bfs(start):
seen = [start]
queue = deque([start])
while queue:
v = queue.popleft()
for nb, _ in graph[v]:
if nb not in seen:
seen.append(nb)
queue.append(nb)
return seen
# ['A', 'B', 'C', 'D']
print(bfs("A"))
Worked example
Task: a directed graph has edges P to Q, P to R and Q to R (no weights). Write it as an adjacency list and as a matrix, and say whether R can be reached from Q.
Adjacency list:
digraph = {"P": ["Q", "R"], "Q": ["R"], "R": []}
Adjacency matrix (rows are the from vertex, columns the to vertex):
P Q R
P [ 0, 1, 1 ]
Q [ 0, 0, 1 ]
R [ 0, 0, 0 ]
Not symmetrical (it's directed). R can be reached from Q: digraph["Q"] contains R, and matrix[Q][R] = 1. Q can't be reached from R (R has no outgoing edges).
Exam tip: for an undirected graph, set both [a][b] and [b][a] (or add to both lists). Be clear about row and column meaning in a directed matrix (from, to). Say which representation you chose and why (few edges: a list; quick edge checks: a matrix).
Check yourself
What does matrix[1][3] hold in a weighted graph matrix?
The weight of the edge from vertex 1 to vertex 3, or 0 (or infinity) if there is none.
How do you add an edge between A and B in an undirected adjacency list?
Add B to A's list and A to B's list.
Why is an adjacency list better for a graph with few edges?
It stores only the edges that exist, using V + E memory, instead of V² cells.
How can you tell an adjacency matrix is for an undirected graph?
It is symmetrical: the value at [i][j] equals the value at [j][i].