Kodewick
Start learning →
Storing a graph: adjacency matrix and list30 / 52

Storing a graph: adjacency matrix and list

Lesson 30 of 52 · Part 6 · Graphs · about 17 minutes

A graph is stored as an adjacency matrix, an n × n table that tells in one step whether two vertices are joined, or as an adjacency list of each vertex's neighbours, a vector<vector<int>> that is far smaller for sparse graphs.

A city map has ten thousand junctions, each joined to three or four roads on average. Before a navigation app can find a route, it has to get "what is joined to what" into memory. The obvious way is a table of ten thousand rows by ten thousand columns, where row i, column j says whether there is a road from i to j: a hundred million boxes, 400 MB as ints, and 99.9% of them are 0. Store only the roads that exist and the same map takes under 2 MB. This lesson covers the two ways to store a graph and when to use which.

Vertices, edges and degree

A graph is made of vertices and the edges joining them. The number of vertices is n, the number of edges e.

  • Edges without a direction make an undirected graph: friendship, where A being B's friend means B is A's friend.
  • Edges with a direction make a directed graph: following someone, one-way streets, course prerequisites. They are drawn as arrows.
  • Edges carrying a number (a distance, a cost, a time) make a weighted graph, and the number is the edge's weight.
  • The number of edges at a vertex is its degree. In a directed graph it splits in two: edges going out give the out-degree, edges coming in the in-degree.

An undirected graph with 5 vertices and 5 edges. Every edge joins two vertices, so the degrees always add up to twice the number of edges

A few words used later: if you can get from one vertex to another along edges, the two are connected; an undirected graph where every pair is connected is a connected graph. An undirected graph on n vertices has at most n(n − 1) / 2 edges. Few edges (e about the size of n) make a sparse graph; close to the maximum, a dense graph.

Choose one

An undirected graph has 7 edges. What do the degrees of all its vertices add up to?

Choose one

An undirected graph has 6 vertices (no repeated edges, no edge from a vertex to itself). What is the most edges it can have?

Adjacency matrix: an n × n table

Use a 2D array int a[N][N]: if i and j are joined, a[i][j] = 1, otherwise 0. An undirected edge is recorded at both ends, so the matrix is symmetric about the diagonal. In a weighted graph the 1 becomes the weight, and a missing edge gets a huge number (such as INT_MAX, meaning "no way through").

01234000000100000200000300000400000

The 5 edges 0–1, 0–2, 1–2, 1–3, 3–4 going into the adjacency matrix one at a time: each undirected edge fills two boxes
main.cpp
1#include <iostream>2using namespace std;3 4const int N = 5;5 6int a[N][N];   // a global array starts as all 07 8void add(int u, int v) {   // undirected edge: record both ends9    a[u][v] = 1;10    a[v][u] = 1;11}12 13int main() {14    add(0, 1);15    add(0, 2);16    add(1, 2);17    add(1, 3);18    add(3, 4);19    for (int i = 0; i < N; i++) {20        int deg = 0;21        for (int j = 0; j < N; j++) {22            cout << a[i][j] << ' ';23            deg += a[i][j];24        }25        cout << "  degree of " << i << " = " << deg << '\n';26    }27    return 0;28}
Output
0 1 1 0 0   degree of 0 = 2
1 0 1 1 0   degree of 1 = 3
1 1 0 0 0   degree of 2 = 2
0 1 0 0 1   degree of 3 = 2
0 0 0 1 0   degree of 4 = 1

A directed graph records one end only: a[u][v] = 1 means u points to v. Then the 1s in row i give i's out-degree, the 1s in column i its in-degree, and the matrix is usually not symmetric. If the number of vertices isn't known at compile time, use vector<vector<int>> a(n, vector<int>(n, 0)); everything else stays the same.

Choose one

In a directed graph's adjacency matrix, column 2 has three 1s. What does that tell you?

Exercise 1

Out-degree and in-degree

a is the adjacency matrix of a directed graph (a[i][j] = 1 means i points to j). Fill in the loop to find each vertex's out-degree (the sum of row i) and in-degree (the sum of column i).

It should print
0: out 2 in 1
1: out 2 in 1
2: out 1 in 2
3: out 1 in 2
exercise1.cpp
1#include <iostream>2using namespace std;3 4const int N = 4;5 6int a[N][N] = {7    {0, 1, 1, 0},8    {0, 0, 1, 1},9    {0, 0, 0, 1},10    {1, 0, 0, 0},11};12 13int main() {14    for (int i = 0; i < N; i++) {15        int out = 0, in = 0;16        // out-degree: add up a[i][0..N-1]; in-degree: add up a[0..N-1][i]17        cout << i << ": out " << out << " in " << in << '\n';18    }19    return 0;20}
Output
Press Run or Ctrl+Enter

Adjacency list: a row of neighbours per vertex

The trouble with the matrix is that it takes n² boxes whether the edges are there or not. An adjacency list stores only the edges that exist. First by hand: an array of n pointers head, where head[i] points to a linked list holding all of i's neighbours. A new neighbour is a node made with new and put at the front of the chain, O(1), with no walk to the end.

0nullptr1nullptr2nullptr3nullptr4nullptr

The adjacency list of the same graph: edges come in as 0–1, 0–2, 1–2, 1–3, 3–4, each putting a node at both ends, always at the front of the chain

Notice that a chain holds its neighbours in the reverse of the order the edges were added: that is the price of inserting at the front. Traversals later visit neighbours in chain order, so the same graph stored differently can be traversed in a different order. Every node made with new has to be given back with delete at the end.

main.cpp
1#include <iostream>2using namespace std;3 4const int N = 5;5 6struct Node {7    int v;          // which neighbour8    Node* next;9    Node(int v, Node* next) : v(v), next(next) {}10};11 12Node* head[N];      // a global array starts as all nullptr13 14void push(int u, int v) {   // put v at the front of u's chain15    head[u] = new Node(v, head[u]);16}17 18void add(int u, int v) {    // undirected edge: one push at each end19    push(u, v);20    push(v, u);21}22 23int main() {24    add(0, 1);25    add(0, 2);26    add(1, 2);27    add(1, 3);28    add(3, 4);29    for (int i = 0; i < N; i++) {30        cout << i << ":";31        for (Node* p = head[i]; p; p = p->next)32            cout << ' ' << p->v;33        cout << '\n';34    }35    for (int i = 0; i < N; i++)     // done: give the nodes back one by one36        while (head[i]) {37            Node* p = head[i];38            head[i] = p->next;39            delete p;40        }41    return 0;42}
Output
0: 2 1
1: 3 2 0
2: 1 0
3: 4 1
4: 3
Guess the outputA wrong guess is fine

A directed graph gets the edges 0→1, 0→2, 2→3, 0→3 in that order. What is on vertex 0's chain?

1#include <iostream>2using namespace std;3 4struct Node {5    int v;6    Node* next;7    Node(int v, Node* next) : v(v), next(next) {}8};9 10Node* head[4];11 12void push(int u, int v) {13    head[u] = new Node(v, head[u]);14}15 16int main() {17    push(0, 1);18    push(0, 2);19    push(2, 3);20    push(0, 3);21    for (Node* p = head[0]; p; p = p->next)22        cout << p->v << ' ';23    cout << '\n';24    return 0;25}
Put in orderDrag, or use the arrows

Put these 4 lines in order so that push(u, v) puts v at the head of u's chain.

  1. p->next = head[u];
  2. p->v = v;
  3. head[u] = p;
  4. Node* p = new Node;
Should print
0: 2 1
1: 2
2:
Exercise 2

Matrix to adjacency list

Turn an undirected graph's adjacency matrix into a hand-made adjacency list, with each chain's neighbours in increasing order. New nodes can only go at the front, so j has to run from high to low. Fill in the two loops in main.

It should print
0: 1 2 4
1: 0 3
2: 0 3 4
3: 1 2
4: 0 2
exercise2.cpp
1#include <iostream>2using namespace std;3 4const int N = 5;5 6struct Node {7    int v;8    Node* next;9    Node(int v, Node* next) : v(v), next(next) {}10};11 12Node* head[N];13 14int a[N][N] = {15    {0, 1, 1, 0, 1},16    {1, 0, 0, 1, 0},17    {1, 0, 0, 1, 1},18    {0, 1, 1, 0, 0},19    {1, 0, 1, 0, 0},20};21 22void push(int u, int v) {23    head[u] = new Node(v, head[u]);24}25 26int main() {27    // for each i, j from N - 1 down to 0: if a[i][j] is 1, push(i, j)28    for (int i = 0; i < N; i++) {29        cout << i << ":";30        for (Node* p = head[i]; p; p = p->next)31            cout << ' ' << p->v;32        cout << '\n';33    }34    for (int i = 0; i < N; i++)35        while (head[i]) {36            Node* p = head[i];37            head[i] = p->next;38            delete p;39        }40    return 0;41}
Output
Press Run or Ctrl+Enter

Which is better: it depends on the edges

First the arithmetic: a graph with ten thousand vertices and fifty thousand undirected edges (average degree 10). How much memory does each way take?

main.cpp
1#include <cstdio>2 3struct Node {4    int v;5    Node* next;6};7 8int main() {9    long long n = 10000, e = 50000;10    long long matrix = n * n * sizeof(int);                      // n × n boxes11    long long list = n * sizeof(Node*) + 2 * e * sizeof(Node);   // n heads + 2e nodes12    printf("adjacency matrix: %lld bytes (about %lld MB)\n", matrix, matrix / 1000000);13    printf("adjacency list:   %lld bytes (about %.1f MB)\n", list, list / 1000000.0);14    printf("one node: %d bytes (int 4 + pointer 8, padded to a multiple of 8)\n", (int)sizeof(Node));15    printf("boxes holding 1 in the matrix: %.2f%%\n", 2.0 * e / (n * n) * 100);16    return 0;17}
Output
adjacency matrix: 400000000 bytes (about 400 MB)
adjacency list:   1680000 bytes (about 1.7 MB)
one node: 16 bytes (int 4 + pointer 8, padded to a multiple of 8)
boxes holding 1 in the matrix: 0.10%

Only 0.1% of the matrix's hundred million boxes are 1. A sparse graph like this (real road networks and social networks nearly all are) goes in an adjacency list; with few vertices and many edges, or when you keep asking "is there an edge between i and j, and what's its weight", use the matrix.

Adjacency matrixAdjacency list
SpaceO(n²)O(n + e)
Is there an edge i–j?O(1)O(degree of i)
All neighbours of iO(n), scan a rowO(degree of i)
Traverse the whole graphO(n²)O(n + e)
Good fordense graphs, modest n (hundreds to thousands)sparse graphs, large n
Unique?yesno (neighbours can be in any order)

Exams like to ask: the number of 1s in an undirected graph's adjacency matrix is 2e, in a directed one e; the non-zero entries in row i (column i) give the out-degree (in-degree); an undirected graph with n vertices and e edges has 2e edge nodes in its adjacency list, a directed one e; and "the adjacency list of a graph is not unique" is a favourite true-or-false.

Choose one

An undirected graph with 1000 vertices and 3000 edges is stored as an adjacency list. How many nodes are there on all the chains together?

Choose one

300 vertices with an edge between almost every pair, and the program keeps asking "what is the weight between i and j". Which way of storing it?

With the STL

Almost nobody hand-writes linked lists for a graph in C++: vector<vector<int>> adj(n) is the adjacency list. adj[i] is a vector<int> holding i's neighbours; adding an edge is adj[u].push_back(v), which goes on the end, so the neighbours keep the same order the edges were added in, the opposite of the hand-written list, which inserts at the front.

01234

The same 5 edges stored in a vector<vector<int>>: push_back adds at the end, so neighbours stay in the order the edges came

For a weighted graph each neighbour becomes a pair<int, int>: first is the neighbour, second the weight.

main.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int main() {7    int n = 5;8    vector<vector<int>> adj(n);          // n empty vectors9    int edges[5][2] = {{0, 1}, {0, 2}, {1, 2}, {1, 3}, {3, 4}};10    for (auto& e : edges) {11        adj[e[0]].push_back(e[1]);       // undirected edge: add at both ends12        adj[e[1]].push_back(e[0]);13    }14    for (int i = 0; i < n; i++) {15        cout << i << ":";16        for (int v : adj[i]) cout << ' ' << v;17        cout << "  (degree " << adj[i].size() << ")\n";18    }19 20    vector<vector<pair<int, int>>> g(n); // weighted: {neighbour, weight}21    int w[5][3] = {{0, 1, 4}, {0, 2, 1}, {1, 2, 2}, {1, 3, 5}, {3, 4, 3}};22    for (auto& e : w) {23        g[e[0]].push_back({e[1], e[2]});24        g[e[1]].push_back({e[0], e[2]});25    }26    for (auto& p : g[1])27        cout << "1 - " << p.first << " weight " << p.second << '\n';28    return 0;29}
Output
0: 1 2  (degree 2)
1: 0 2 3  (degree 3)
2: 0 1  (degree 2)
3: 1 4  (degree 2)
4: 3  (degree 1)
1 - 0 weight 4
1 - 2 weight 2
1 - 3 weight 5

What's inside: the outer vector is n vector<int>s side by side, 24 bytes each (a pointer to the data, the size, the capacity); each inner vector is a growing array with the neighbours next to each other and no next pointers. Ten thousand vertices, fifty thousand edges: 10000 × 24 + 100000 × 4 = 640 000 bytes, about 1 MB even with the spare room push_back leaves, less than the hand-made list's 1.7 MB, and faster to walk because the neighbours sit together. A vector frees itself; no delete.

OperationCodeCost
Make n verticesvector<vector<int>> adj(n)O(n)
Add an edgeadj[u].push_back(v)amortised O(1)
Degree of uadj[u].size()O(1)
Walk u's neighboursfor (int v : adj[u])O(degree of u)
Is there an edge u–v?find(adj[u].begin(), adj[u].end(), v)O(degree of u)
Same, with vector<set<int>>adj[u].count(v)O(log degree)

In interviews: the problem usually gives n and an array of edges edges, and the first thing you write is those three lines: vector<vector<int>> adj(n); and a loop of push_back, remembering both ends for an undirected graph. Weighted means vector<vector<pair<int, int>>>. Reach for a matrix only when n is small (a few hundred) and you keep asking "is there an edge". Grid (maze) problems need no graph at all: the neighbours of cell (r, c) are the four cells around it.

Guess the outputA wrong guess is fine

A directed graph gets the edges 0→1, 0→2, 2→3, 0→3 in that order, this time stored in a vector<vector<int>>. What is in adj[0], in order?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<vector<int>> adj(4);7    adj[0].push_back(1);8    adj[0].push_back(2);9    adj[2].push_back(3);10    adj[0].push_back(3);11    for (int v : adj[0])12        cout << v << " ";13    cout << "\n";14    return 0;15}
Choose one

A vector<vector<int>> adj(n) holds an undirected graph with n vertices and e edges. How many ints are there in all the adj[i] put together?

Summary

Take-away

Two ways to store a graph

  • Degrees add up to 2e; directed graphs split out-degree and in-degree
  • Adjacency matrix int a[N][N]: O(n²) space, edge lookup O(1), for dense graphs
  • Adjacency list: O(n + e) space, for sparse graphs; by hand, front inserts reverse the order
  • In C++ use vector<vector<int>>; weighted means pair<neighbour, weight>
1vector<vector<int>> adj(n);2adj[u].push_back(v);   // directed edge u → v3adj[v].push_back(u);   // add this too for an undirected graph4for (int v : adj[u])5    cout << v << ' ';