Adjacency Lists and Adjacency Matrices
Before an algorithm can walk a graph, the graph has to live in memory. There are two standard layouts. An adjacency list stores, for every vertex, the list of its neighbours. An adjacency matrix stores a table of bits, one per possible edge. They answer different questions at different speeds, and the choice decides the running time of nearly every algorithm in this course. The Graph Implementation lesson of the DSA course builds both by example; this lesson measures them.
The two layouts
Number the vertices (or name them with letters and map the letters to numbers).
- Adjacency lists. An array of lists. For a directed graph, holds every with an edge , so the lists have entries in total. For an undirected graph each edge appears twice, once in and once in , for entries. The space is either way.
- Adjacency matrix. A array with if and otherwise. For an undirected graph the matrix is symmetric, , and only the upper triangle needs storing. The space is regardless of how many edges there are.
For a weighted graph, the list entries are pairs , and the matrix holds the weight itself, with a special value (0, or a missing marker) for "no edge". Which marker is right depends on the algorithm: the shortest-path matrices of Floyd-Warshall use .
names = "ABCDE"
idx = {v: i for i, v in enumerate(names)}
edges = [("A", "B"), ("A", "D"), ("B", "C"), ("C", "A"), ("D", "C"), ("D", "E"), ("E", "B")] # directed
adj = {v: [] for v in names}
for u, v in edges:
adj[u].append(v)
for v in names:
adj[v].sort() # alphabetical neighbour order, as in every lesson
matrix = [[0] * len(names) for _ in names]
for u, v in edges:
matrix[idx[u]][idx[v]] = 1
print("adjacency lists:")
for v in names:
print(f" {v}: {adj[v]}")
print("adjacency matrix (row = from, column = to):")
print(" " + " ".join(names))
for u in names:
print(f" {u} " + " ".join(str(b) for b in matrix[idx[u]]))
print("list entries:", sum(len(a) for a in adj.values()), " matrix cells:", len(names) ** 2)adjacency lists:
A: ['B', 'D']
B: ['C']
C: ['A']
D: ['C', 'E']
E: ['B']
adjacency matrix (row = from, column = to):
A B C D E
A 0 1 0 1 0
B 0 0 1 0 0
C 1 0 0 0 0
D 0 0 1 0 1
E 0 1 0 0 0
list entries: 7 matrix cells: 25
Row of the matrix is the adjacency list of written as a bit vector, and column lists the vertices with an edge into . The lists hold exactly entries, the matrix 25 cells.
What each layout does fast
| Operation | Adjacency lists | Adjacency matrix |
|---|---|---|
| space | ||
| is an edge? | : scan | : read |
| visit all neighbours of | : scan row | |
| visit every edge | ||
| add an edge | (append) | |
| compute the transpose | , or free by reading columns |
Searches, spanning trees and shortest paths all "visit every edge", so with adjacency lists they run in time close to , and with a matrix they cannot beat . That is why lists are the default for sparse graphs, and road networks, the web and most real networks are very sparse: a road junction has a handful of roads, not thousands. A matrix wins when the graph is dense, when the algorithm needs constant-time edge queries, or when it is naturally a matrix algorithm, such as shortest paths by matrix multiplication and transitive closure.
The program measures both layouts on a sparse and on a dense graph of 200 vertices. It counts cells read while visiting every edge once, and while answering 1000 edge queries.
import random
def make(n, m, seed):
rng = random.Random(seed)
pairs = set()
while len(pairs) < m:
u, v = rng.randrange(n), rng.randrange(n)
if u != v:
pairs.add((u, v))
return sorted(pairs)
def measure(n, edges, queries):
adj = [[] for _ in range(n)]
mat = [[0] * n for _ in range(n)]
for u, v in edges:
adj[u].append(v)
mat[u][v] = 1
visit_list = sum(1 + len(adj[u]) for u in range(n)) # one read per list head and per entry
visit_mat = n * n # every cell of every row
query_list = 0
for u, v in queries:
for x in adj[u]:
query_list += 1
if x == v:
break
query_mat = len(queries) # one cell each
return visit_list, visit_mat, query_list, query_mat
n = 200
rng = random.Random(1)
queries = [(rng.randrange(n), rng.randrange(n)) for _ in range(1000)]
print(f"{'graph':>18} {'visit: lists':>13} {'matrix':>8} {'1000 queries: lists':>20} {'matrix':>7}")
for name, m in [("sparse, E = 600", 600), ("dense, E = 30000", 30000)]:
vl, vm, ql, qm = measure(n, make(n, m, 2), queries)
print(f"{name:>18} {vl:>13} {vm:>8} {ql:>20} {qm:>7}") graph visit: lists matrix 1000 queries: lists matrix
sparse, E = 600 800 40000 3036 1000
dense, E = 30000 30200 40000 94707 1000
On the sparse graph the lists visit every edge in about 800 reads against the matrix's 40,000, and even edge queries cost only about three reads each because the lists are short. On the dense graph (three quarters of all possible edges) the two layouts visit edges at similar cost, and the matrix answers each query in one read while the lists scan about a hundred entries.
Note: A hash set per vertex gives expected edge queries with space, the best of both for many programs. Its neighbours come out in no particular order, though, so code that must be deterministic sorts them, as this course does.
In C++
In C++ the usual adjacency list is a std::vector<std::vector<int>>, and a weighted one stores std::pair<int, int> entries. The program builds both layouts for the five-vertex graph above, prints the lists, and computes the transpose from the lists in time.
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
int main() {
const std::string names = "ABCDE";
const int n = static_cast<int>(names.size());
std::vector<std::pair<int, int>> edges = {{0, 1}, {0, 3}, {1, 2}, {2, 0}, {3, 2}, {3, 4}, {4, 1}};
std::vector<std::vector<int>> adj(n);
std::vector<std::vector<char>> mat(n, std::vector<char>(n, 0));
for (auto [u, v] : edges) { adj[u].push_back(v); mat[u][v] = 1; }
std::vector<std::vector<int>> rev(n); // transpose: reverse every edge
for (int u = 0; u < n; ++u)
for (int v : adj[u]) rev[v].push_back(u);
for (int u = 0; u < n; ++u) {
std::printf("%c: out", names[u]);
for (int v : adj[u]) std::printf(" %c", names[v]);
std::printf(" | in");
for (int v : rev[u]) std::printf(" %c", names[v]);
std::printf("\n");
}
std::printf("is D->C an edge? %d is C->D an edge? %d\n", mat[3][2], mat[2][3]);
}A: out B D | in C
B: out C | in A E
C: out A | in B D
D: out C E | in A
E: out B | in D
is D->C an edge? 1 is C->D an edge? 0
Test yourself
An undirected graph with vertices and edges is stored as adjacency lists. How many list entries are there in total?
Which operation is faster with an adjacency matrix than with adjacency lists?
- Visiting all edges of a sparse graph
- Listing the neighbours of a vertex of small degree
- Testing whether a given pair is an edge
- Storing a graph with
Why does an algorithm that visits every edge take time on an adjacency matrix, even when is small?
- Because every edge is stored twice
- Because finding the neighbours of a vertex means scanning its whole row of cells
- Because matrices must be sorted first
- It does not: it takes