TExcelTAD
Home › Graph Algorithms › Adjacency Lists and Adjacency Matrices

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 V×VV \times V 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 0,1,…,V−10, 1, \ldots, V - 1 (or name them with letters and map the letters to numbers).

  • Adjacency lists. An array Adj\textit{Adj} of VV lists. For a directed graph, Adj[u]\textit{Adj}[u] holds every vv with an edge (u,v)(u, v), so the lists have EE entries in total. For an undirected graph each edge {u,v}\{u, v\} appears twice, once in Adj[u]\textit{Adj}[u] and once in Adj[v]\textit{Adj}[v], for 2E2E entries. The space is Θ(V+E)\Theta(V + E) either way.
  • Adjacency matrix. A V×VV \times V array AA with auv=1a_{uv} = 1 if (u,v)∈E(u, v) \in E and auv=0a_{uv} = 0 otherwise. For an undirected graph the matrix is symmetric, A=ATA = A^{\mathsf{T}}, and only the upper triangle needs storing. The space is Θ(V2)\Theta(V^2) regardless of how many edges there are.

For a weighted graph, the list entries are pairs (v,w(u,v))(v, w(u, v)), and the matrix holds the weight itself, with a special value (0, ∞\infty or a missing marker) for "no edge". Which marker is right depends on the algorithm: the shortest-path matrices of Floyd-Warshall use ∞\infty.

python · try it yourself
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 uu of the matrix is the adjacency list of uu written as a bit vector, and column vv lists the vertices with an edge into vv. The lists hold exactly E=7E = 7 entries, the matrix 25 cells.

What each layout does fast

Operation Adjacency lists Adjacency matrix
space Θ(V+E)\Theta(V + E) Θ(V2)\Theta(V^2)
is (u,v)(u, v) an edge? O(deg⁡(u))O(\deg(u)): scan Adj[u]\textit{Adj}[u] Θ(1)\Theta(1): read auva_{uv}
visit all neighbours of uu Θ(deg⁡(u))\Theta(\deg(u)) Θ(V)\Theta(V): scan row uu
visit every edge Θ(V+E)\Theta(V + E) Θ(V2)\Theta(V^2)
add an edge O(1)O(1) (append) Θ(1)\Theta(1)
compute the transpose GTG^{\mathsf{T}} Θ(V+E)\Theta(V + E) Θ(V2)\Theta(V^2), 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 V+EV + E, and with a matrix they cannot beat V2V^2. 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.

python · try it yourself
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 O(1)O(1) edge queries with Θ(V+E)\Theta(V + E) 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 Θ(V+E)\Theta(V + E) time.

cpp · try it yourself
#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 VV vertices and EE edges is stored as adjacency lists. How many list entries are there in total?

  1. EE
  2. 2E2E
  3. V+EV + E
  4. V2V^2

Which operation is faster with an adjacency matrix than with adjacency lists?

  1. Visiting all edges of a sparse graph
  2. Listing the neighbours of a vertex of small degree
  3. Testing whether a given pair (u,v)(u, v) is an edge
  4. Storing a graph with E=VE = V

Why does an algorithm that visits every edge take Ω(V2)\Omega(V^2) time on an adjacency matrix, even when EE is small?

  1. Because every edge is stored twice
  2. Because finding the neighbours of a vertex means scanning its whole row of VV cells
  3. Because matrices must be sorted first
  4. It does not: it takes Θ(V+E)\Theta(V + E)