Kodewick
Start learning →
Storing graphs: adjacency matrices and lists28 / 50

Storing graphs: adjacency matrix and adjacency list

Lesson 28 of 50 · Part 6 · Graphs · about 16 minutes

An adjacency matrix stores a graph as an n × n table where a[i][j] says in one step whether i and j are joined; an adjacency list keeps one chain of neighbours per vertex, takes O(n + e) space and suits sparse graphs better.

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 joins what" into memory. The most direct way is a table with ten thousand rows and ten thousand columns, row i column j saying whether there's a road from i to j: a hundred million boxes, 400 MB as ints, and 99.9% of them are 0. Store it another way, keeping only the roads that exist, and the same map takes under 2 MB. This lesson is about those two ways of storing a graph, and when to use which.

Vertices, edges and degree

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

  • When edges have no direction, it's an undirected graph: friendships. If A is B's friend, B is A's friend.
  • When edges have a direction, it's a directed graph: following someone, one-way streets, course prerequisites. Edges are drawn as arrows.
  • When each edge carries a number (a distance, a cost, a time), it's 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 make 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 from here on: if you can walk from one vertex to another along edges, the two are connected; an undirected graph in which every two vertices are connected is a connected graph. An undirected graph on n vertices has at most n(n − 1) / 2 edges. A graph with few edges (e about as big as n) is sparse; one with nearly all of them is dense.

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 a[n][n]: if there's an edge between i and j, a[i][j] = 1, otherwise 0. An undirected edge is recorded at both ends, so the matrix is symmetric about its diagonal. For a weighted graph the 1 becomes the weight, and a missing edge gets a very large number (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.c
1#include <stdio.h>2 3#define N 54 5int a[N][N];6 7void add(int u, int v) {   // undirected edge: record both ends8    a[u][v] = 1;9    a[v][u] = 1;10}11 12int main(void) {13    add(0, 1);14    add(0, 2);15    add(1, 2);16    add(1, 3);17    add(3, 4);18    for (int i = 0; i < N; i++) {19        int deg = 0;20        for (int j = 0; j < N; j++) {21            printf("%d ", a[i][j]);22            deg += a[i][j];23        }24        printf("  degree of %d = %d\n", i, deg);25    }26    return 0;27}
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 usually isn't symmetric.

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 a directed graph's adjacency matrix (a[i][j] = 1 means i points to j). Finish the loop so it works out every 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.c
1#include <stdio.h>2 3#define N 44 5int a[N][N] = {6    {0, 1, 1, 0},7    {0, 0, 1, 1},8    {0, 0, 0, 1},9    {1, 0, 0, 0},10};11 12int main(void) {13    for (int i = 0; i < N; i++) {14        int out = 0, in = 0;15        // out-degree: add up a[i][0..N-1]; in-degree: add up a[0..N-1][i]16        printf("%d: out %d in %d\n", i, out, in);17    }18    return 0;19}
Output
Press Run or Ctrl+Enter

Adjacency list: one chain per vertex

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

0NULL1NULL2NULL3NULL4NULL

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 the chains come out in the reverse of the order the edges were added: that's 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.

main.c
1#include <stdio.h>2#include <stdlib.h>3 4#define N 55 6typedef struct Node {7    int v;               // which neighbour8    struct Node *next;9} Node;10 11Node *head[N];           // a global array: all NULL to begin with12 13void push(int u, int v) {   // v goes in at the front of u's chain14    Node *p = malloc(sizeof(Node));15    p->v = v;16    p->next = head[u];17    head[u] = p;18}19 20void add(int u, int v) {    // undirected edge: once at each end21    push(u, v);22    push(v, u);23}24 25int main(void) {26    add(0, 1);27    add(0, 2);28    add(1, 2);29    add(1, 3);30    add(3, 4);31    for (int i = 0; i < N; i++) {32        printf("%d:", i);33        for (Node *p = head[i]; p; p = p->next)34            printf(" %d", p->v);35        printf("\n");36    }37    return 0;38}
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's on vertex 0's chain?

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int v;6    struct Node *next;7} Node;8 9Node *head[4];10 11void push(int u, int v) {12    Node *p = malloc(sizeof(Node));13    p->v = v;14    p->next = head[u];15    head[u] = p;16}17 18int main(void) {19    push(0, 1);20    push(0, 2);21    push(2, 3);22    push(0, 3);23    for (Node *p = head[0]; p; p = p->next)24        printf("%d ", p->v);25    printf("\n");26    return 0;27}
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 = malloc(sizeof(Node));
Should print
0: 2 1
1: 2
2:
Exercise 2

Matrix to adjacency list

Turn an undirected graph's adjacency matrix into an adjacency list, with every chain's neighbours in increasing order. New nodes can only go in at the front, so j has to run from large to small. Finish 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.c
1#include <stdio.h>2#include <stdlib.h>3 4#define N 55 6typedef struct Node {7    int v;8    struct Node *next;9} Node;10 11Node *head[N];12 13int a[N][N] = {14    {0, 1, 1, 0, 1},15    {1, 0, 0, 1, 0},16    {1, 0, 0, 1, 1},17    {0, 1, 1, 0, 0},18    {1, 0, 1, 0, 0},19};20 21void push(int u, int v) {22    Node *p = malloc(sizeof(Node));23    p->v = v;24    p->next = head[u];25    head[u] = p;26}27 28int main(void) {29    // for each i, j from N - 1 down to 0: if a[i][j] is 1, push(i, j)30    for (int i = 0; i < N; i++) {31        printf("%d:", i);32        for (Node *p = head[i]; p; p = p->next)33            printf(" %d", p->v);34        printf("\n");35    }36    return 0;37}
Output
Press Run or Ctrl+Enter

Which is better: it depends on the edges

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

main.c
1#include <stdio.h>2 3typedef struct Node {4    int v;5    struct Node *next;6} Node;7 8int main(void) {9    long n = 10000, e = 50000;10    long matrix = n * n * sizeof(int);                     // n × n boxes11    long list = n * sizeof(Node *) + 2 * e * sizeof(Node); // n heads + 2e nodes12    printf("adjacency matrix: %ld bytes (about %ld MB)\n", matrix, matrix / 1000000);13    printf("adjacency list:   %ld bytes (about %.1f MB)\n", list, list / 1000000.0);14    printf("boxes in the matrix that are 1: %.2f%%\n", 2.0 * e / (n * n) * 100);15    return 0;16}
Output
adjacency matrix: 400000000 bytes (about 400 MB)
adjacency list:   1680000 bytes (about 1.7 MB)
boxes in the matrix that are 1: 0.10%

Of the matrix's hundred million boxes, 0.1% are 1. A sparse graph like this (real road networks and social networks nearly all are) wants an adjacency list; few vertices and lots of edges, or a lot of "is there an edge between i and j, and what's its weight?", wants a matrix.

Adjacency matrixAdjacency list
SpaceO(n²)O(n + e)
Is there an edge between i and j?O(1)O(degree of i)
All of i's neighboursO(n), a whole rowO(degree of i)
Traversing the whole graphO(n²)O(n + e)
Good fordense graphs, n not big (hundreds to thousands)sparse graphs, big n
Is it unique?yesno (chains can be in different orders)

In exams: "the number of 1s in an undirected graph's adjacency matrix" is 2e, and e for a directed graph; "the number of nonzero entries in row (column) i" is 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. "An adjacency list isn't unique" is a favourite true/false question too. Some exams also cover the orthogonal list (directed graphs) and the adjacency multilist (undirected graphs); it's enough to know they exist so that each edge is stored only once.

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?

Summary

Take-away

Two ways to store a graph

  • Degrees add up to 2e; a directed graph has out-degree and in-degree
  • Adjacency matrix a[n][n]: O(n²) space, edge lookup O(1), for dense graphs
  • Adjacency list head[n] + chains: O(n + e) space, for sparse graphs
  • Undirected edges go in at both ends; front insertion reverses the order
1void push(int u, int v) {2    Node *p = malloc(sizeof(Node));3    p->v = v;4    p->next = head[u];5    head[u] = p;6}