Graph Implementation
There are two standard ways to store a graph in memory: an adjacency matrix and an adjacency list. Both store the same information; they differ in memory use and in which questions they answer quickly.
We'll use this undirected graph with 5 vertices and 6 edges throughout the lesson:
A ─── B
│ ╱ │
│ ╱ │
C ─── D ─── EEdges: A-B, A-C, B-C, B-D, C-D, D-E.
Adjacency matrix
Number the vertices 0 .. n-1 and use an n × n table: matrix[i][j] is 1 if there is an edge from i to j, otherwise 0. For an undirected graph the matrix is symmetric.
names = ["A", "B", "C", "D", "E"]
index = {name: i for i, name in enumerate(names)}
n = len(names)
matrix = [[0] * n for _ in range(n)]
for edge in ["A-B", "A-C", "B-C", "B-D", "C-D", "D-E"]:
a, b = edge.split("-")
matrix[index[a]][index[b]] = 1
matrix[index[b]][index[a]] = 1 # undirected: both directions
print(" " + " ".join(names))
for name, row in zip(names, matrix):
print(name, " ".join(map(str, row)))
print("edge B-D?", bool(matrix[index["B"]][index["D"]]))
print("neighbours of C:", [names[j] for j in range(n) if matrix[index["C"]][j]]) A B C D E
A 0 1 1 0 0
B 1 0 1 1 0
C 1 1 0 1 0
D 0 1 1 0 1
E 0 0 0 1 0
edge B-D? True
neighbours of C: ['A', 'B', 'D']
Checking for a specific edge is O(1): one table lookup. Finding all neighbours of a vertex needs a scan of its whole row, O(n), even if it has only one neighbour. The table always takes n² cells.
For a weighted graph, store the weight instead of 1 and use None (or infinity) for "no edge".
Adjacency list
Store, for each vertex, only the list of its neighbours. A dictionary of lists is the natural Python form:
from collections import defaultdict
adj = defaultdict(list)
for edge in ["A-B", "A-C", "B-C", "B-D", "C-D", "D-E"]:
a, b = edge.split("-")
adj[a].append(b)
adj[b].append(a)
for v in sorted(adj):
print(v, "->", adj[v])
print("edge B-D?", "D" in adj["B"])
print("degree of D:", len(adj["D"]))A -> ['B', 'C']
B -> ['A', 'C', 'D']
C -> ['A', 'B', 'D']
D -> ['B', 'C', 'E']
E -> ['D']
edge B-D? True
degree of D: 3
Listing the neighbours of v takes time proportional to its degree, and the total memory is O(V + E): one entry per vertex plus two per undirected edge.
Which one to choose?
| Adjacency matrix | Adjacency list | |
|---|---|---|
| Memory | O(V²) |
O(V + E) |
Is there an edge u-v? |
O(1) |
O(degree(u)) (or O(1) with sets) |
Iterate over neighbours of u |
O(V) |
O(degree(u)) |
| Add an edge | O(1) |
O(1) |
| Best for | dense graphs (many edges), small V |
sparse graphs (few edges per vertex), most real graphs |
Real-world graphs are usually sparse: a road intersection has a handful of roads, not one to every other intersection. For a million vertices, a matrix would need a trillion cells:
def memory_cells(vertices, avg_degree):
edges = vertices * avg_degree // 2
return vertices * vertices, vertices + 2 * edges
for v, d in [(5, 2), (1_000, 4), (1_000_000, 4)]:
matrix, lists = memory_cells(v, d)
print(f"V={v:>9,}: matrix {matrix:>17,} cells, adjacency list {lists:>9,} cells")V= 5: matrix 25 cells, adjacency list 15 cells
V= 1,000: matrix 1,000,000 cells, adjacency list 5,000 cells
V=1,000,000: matrix 1,000,000,000,000 cells, adjacency list 5,000,000 cells
A reusable Graph class
Here is a small class supporting directed or undirected, weighted or unweighted graphs. Later lessons use the same structure: a dictionary from vertex to a dictionary of {neighbour: weight}.
class Graph:
def __init__(self, directed=False):
self.directed = directed
self.adj = {}
def add_vertex(self, v):
self.adj.setdefault(v, {})
def add_edge(self, u, v, weight=1):
self.add_vertex(u)
self.add_vertex(v)
self.adj[u][v] = weight
if not self.directed:
self.adj[v][u] = weight
def neighbours(self, v):
return sorted(self.adj[v])
def has_edge(self, u, v):
return v in self.adj.get(u, {})
def edges(self):
seen = set()
for u in self.adj:
for v, w in self.adj[u].items():
if self.directed or (v, u) not in seen:
seen.add((u, v))
yield u, v, w
city = Graph()
for u, v, km in [("Oslo", "Bergen", 463), ("Oslo", "Trondheim", 494), ("Bergen", "Stavanger", 209)]:
city.add_edge(u, v, km)
print(city.neighbours("Oslo"))
print(city.has_edge("Bergen", "Oslo"), city.has_edge("Oslo", "Stavanger"))
print(list(city.edges()))
tasks = Graph(directed=True)
tasks.add_edge("design", "build")
tasks.add_edge("build", "test")
print(tasks.has_edge("build", "test"), tasks.has_edge("test", "build"))['Bergen', 'Trondheim']
True False
[('Oslo', 'Bergen', 463), ('Oslo', 'Trondheim', 494), ('Bergen', 'Stavanger', 209)]
True False
Tip: Using a dictionary (or set) of neighbours instead of a list makes "is there an edge?" an
O(1)check while keeping the memory of an adjacency list.
Edge lists
A third, simpler form is just a list of edges [(u, v, weight), …]. It is awkward for finding neighbours, but perfect for algorithms that process edges one by one in some order, such as Kruskal's minimum spanning tree and Bellman-Ford's shortest paths.
Test yourself
How much memory does an adjacency matrix need for a graph with V vertices?
- O(V)
- O(E)
- O(V + E)
- O(V²)
Which representation is usually better for a large, sparse graph such as a road network?
- Adjacency matrix
- Adjacency list
- They are equally good
- Neither can store it
In an adjacency matrix of an undirected graph, what is always true?
- The diagonal is all 1s
- matrix[i][j] == matrix[j][i]
- Every row sums to 1
- It has more 1s than 0s