Edexcel International Advanced Level Computer Science, point 14.1.3
Definition
A graph is a data structure made of vertices (nodes) joined by edges (links). It models relationships and connections: road maps, computer networks, social networks, web pages and their links, flight routes, dependencies between tasks.
Function and why needed
Many problems are really about connections. Representing them as a graph lets you use standard algorithms: shortest path (Dijkstra's, 15.2.3), traversal, spanning trees, routing (12.1.3).
a. Structure
- Vertex (node): a point (a town, a person, a router).
- Edge: a connection between two vertices.
- Adjacent vertices: joined by an edge. The degree of a vertex is the number of edges attached.
- Path: a sequence of vertices joined by edges. A cycle is a path that returns to its start.
- Connected graph: there is a path between every pair of vertices.
c. Types
| Type | Description | Example |
|---|---|---|
| Undirected | Edges work both ways (no direction) | A road between towns; friendship on a social network |
| Directed (digraph) | Edges have a direction (drawn as arrows) | A one-way street; "follows" on social media; web links |
| Weighted | Each edge has a value (weight): distance, time, cost | Road distances for finding the shortest route |
(A graph can be both directed and weighted.) A tree (14.1.4) is a connected graph with no cycles.
b. Ways to represent a graph
Use this weighted undirected graph for the examples: edges A-B (4), A-C (2), B-D (5), C-D (8).
Adjacency matrix
A 2D array with one row and column for each vertex. The cell [row][col] holds the weight (or 1) if there is an edge, and 0 (or ∞) if not.
| A | B | C | D | |
|---|---|---|---|---|
| A | 0 | 4 | 2 | 0 |
| B | 4 | 0 | 0 | 5 |
| C | 2 | 0 | 0 | 8 |
| D | 0 | 5 | 8 | 0 |
- An undirected graph's matrix is symmetrical (the same either side of the diagonal).
- A directed graph's matrix has an entry only in the direction of the edge.
vertices = ["A", "B", "C", "D"]
matrix = [
[0, 4, 2, 0],
[4, 0, 0, 5],
[2, 0, 0, 8],
[0, 5, 8, 0],
]
print(matrix[0][1]) # weight of edge A-B: 4
- Benefits: checking whether an edge exists is , simple, and good for dense graphs (many edges).
- Drawbacks: uses memory, wasteful for sparse graphs (few edges), and finding all neighbours means scanning a row ().
Adjacency list
For each vertex, a list of the vertices it is joined to (with weights).
graph = {
"A": [("B", 4), ("C", 2)],
"B": [("A", 4), ("D", 5)],
"C": [("A", 2), ("D", 8)],
"D": [("B", 5), ("C", 8)],
}
print(graph["A"]) # neighbours of A: [('B', 4), ('C', 2)]
- Benefits: memory use is (efficient for sparse graphs), and finding a vertex's neighbours is quick.
- Drawbacks: checking for a particular edge means scanning a list (), and a bit more complex.
| Adjacency matrix | Adjacency list | |
|---|---|---|
| Memory | ||
| Is there an edge A-B? | ||
| Neighbours of a vertex | Quick (just the list) | |
| Best for | Dense graphs | Sparse graphs (most real ones) |
d. Operations
Insert
- Add a vertex: add a row and column (matrix), or a new dictionary key (list).
- Add an edge: set the matrix cell(s) (both for undirected), or append to the list(s).
def add_edge(graph, a, b, weight):
graph[a].append((b, weight))
graph[b].append((a, weight)) # undirected: add both ways
Delete
- Remove an edge: reset the cell(s), or remove from the list(s).
- Remove a vertex: remove all its edges first, then the vertex.
Search
- Is there a vertex?
"A" in graph. - Is there an edge? Matrix: check the cell. List: scan the neighbour list.
- Is there a path between two vertices? Use a traversal.
Traverse
Visiting every vertex reachable from a start vertex, once each. Keep a visited set so cycles don't cause endless loops.
Breadth-first search (BFS) visits the nearest vertices first, level by level, using a queue (4.3.2).
from collections import deque
def bfs(graph, start):
visited = [start]
queue = deque([start])
while queue:
v = queue.popleft()
for neighbour, _ in graph[v]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
return visited
print(bfs(graph, "A")) # ['A', 'B', 'C', 'D']
Depth-first search (DFS) goes as far as possible along each path before backtracking, using a stack (4.3.1) or recursion.
def dfs(graph, v, visited=None):
if visited is None:
visited = []
visited.append(v)
for neighbour, _ in graph[v]:
if neighbour not in visited:
dfs(graph, neighbour, visited)
return visited
print(dfs(graph, "A")) # ['A', 'B', 'D', 'C']
| Breadth-first | Depth-first | |
|---|---|---|
| Uses | Queue | Stack / recursion |
| Order | Level by level (nearest first) | Deep first, then backtrack |
| Good for | Shortest path in an unweighted graph, nearest neighbours | Exploring all paths, mazes, detecting cycles |
| Time |
Uses
- Shortest routes (satnav, Dijkstra's, 15.2.3), network routing, social networks (friends of friends), web crawlers, scheduling with dependencies, recommendations.
Benefits and drawbacks
- Benefits: models any set of relationships, many well-known algorithms, flexible.
- Drawbacks: more complex than simple lists, can use a lot of memory (matrix), traversals need care with cycles, and big graphs need efficient algorithms.
Worked example
Task: for the graph with edges A-B, A-C, B-D, C-D, D-E, (a) write the adjacency list, (b) give the breadth-first order from A, and (c) the depth-first order from A, taking neighbours in alphabetical order.
(a)
graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A", "D"],
"D": ["B", "C", "E"],
"E": ["D"],
}
(b) BFS: start at A. Queue: A. Visit A: add B, C. Visit B: add D. Visit C: D already seen. Visit D: add E. Visit E. Order: A, B, C, D, E.
(c) DFS: A, then B (first neighbour), then D (B's unvisited neighbour), then C (D's first unvisited neighbour), backtrack, then E. Order: A, B, D, C, E.
Why do they differ? BFS spreads out level by level (A; B, C; D; E), but DFS dives down one path first (A to B to D) and backtracks.
Exam tip: know the two representations and their trade-offs (matrix: memory, fast edge check; list: efficient for sparse graphs). Show the matrix for an undirected graph is symmetrical. For traversals, say which data structure each uses (BFS: queue, DFS: stack), and trace with a visited list.
Check yourself
What is the difference between a directed and an undirected graph?
In a directed graph edges have a direction (one-way); in an undirected graph edges work both ways.
What is a weighted graph, and what might the weights represent?
A graph where each edge has a value, such as distance, time or cost.
Give one advantage of an adjacency list over an adjacency matrix
It uses less memory for sparse graphs (V + E instead of V²) and finding a vertex's neighbours is quick.
Which data structure does a breadth-first search use, and which does a depth-first search use?
Breadth-first uses a queue; depth-first uses a stack (or recursion).
Why must a graph traversal keep track of visited vertices?
So that vertices aren't visited more than once, which would cause infinite loops when the graph has cycles.