CIE AS & A Level Computer Science, section 19.1 (Algorithms)
Graph representation
A graph has nodes and edges (see section 18). Two ways to store one:
Adjacency matrix: a 2D array where matrix[i][j] shows the edge (or its weight) from to .
Adjacency list: for each node, a list of its neighbours.
nodes = ["A", "B", "C", "D"]
matrix = [[0, 1, 1, 0],
[1, 0, 1, 1],
[1, 1, 0, 0],
[0, 1, 0, 0]]
adjacency = {"A": ["B", "C"], "B": ["A", "C", "D"], "C": ["A", "B"], "D": ["B"]}
print(adjacency["B"]) # ['A', 'C', 'D']
| Matrix | List | |
|---|---|---|
| Memory | always | proportional to the edges |
| Is there an edge? | direct check | search the list |
| Suited to | dense graphs | sparse graphs |
Dictionary
A dictionary is an ADT that stores key-value pairs. Each key is unique, and the value is found from the key. Operations: add, look up, change and delete. It is often implemented with hashing (see section 13), so a lookup is fast.
ages = {"Aisha": 17, "Ben": 18}
ages["Cara"] = 16 # add
print(ages["Ben"]) # 18
del ages["Aisha"] # delete
print("Aisha" in ages) # False
Building one ADT from another
An ADT is described by its operations, not its storage. It can be built on top of another.
- A stack or queue can be built from an array or a linked list.
- A queue can be built from two stacks.
- A graph can use a dictionary of lists.
- A binary tree can be built from records and pointers (or an array).
class QueueFromStacks:
def __init__(self):
self.inbox, self.outbox = [], [] # two stacks
def enqueue(self, item):
self.inbox.append(item)
def dequeue(self):
if not self.outbox:
while self.inbox:
self.outbox.append(self.inbox.pop())
return self.outbox.pop()
q = QueueFromStacks()
for x in [1, 2, 3]:
q.enqueue(x)
print(q.dequeue(), q.dequeue()) # 1 2
Programs using the ADT only need its operations, so the storage can change without changing the rest of the program.
Common mistake: thinking a dictionary can hold the same key twice. Each key is unique; adding it again replaces the value. Also, choose an adjacency list for sparse graphs, because a matrix wastes memory.
Exam tip: when asked how to build an ADT, say which structure it is built on and how each operation works on it. Describe the ADT by its operations.
Check yourself
What is stored in an adjacency list?
For each node, a list of the nodes it is joined to.
Why must the keys in a dictionary be unique?
Each key must identify exactly one value, so it can be used to look the value up.
Identify a structure on which a stack can be built.
An array or a linked list.