What is an adjacency list and how do you code one?

user1001776 picture user1001776 · Oct 19, 2011 · Viewed 10.7k times · Source

Here is an SO post of an adjacency list. However I see no difference from a single-linked list? Also here is a wikipedia article which says that it is all the edges (of a graph, discrete math type) in a list which is pretty broad, if I have a graph, which is not a path graph. How do I code an adjacency list?

Answer

Kerrek SB picture Kerrek SB · Oct 19, 2011

A simple example: Suppose you have a vertex type Vertex. They your graph consists of a set of vertices, which you can implement as:

std::unordered_set<Vertex> vertices;

Now for every pair of vertices between which there is an edge in your graph, you need to record that edge. In an adjacency list representation, you would make an edge type which could be a pair of vertices, and your adjacency list could simply be a list (or again a set) of such edges:

typedef std::pair<Vertex, Vertex> Edge;
std::list<Edge> edges_as_list;
std::unordered_set<Edge> edges_as_set;

(You will probably want to supply the last set with an undirected comparator for which (a,b) == (b,a) if you have an undirected graph.)

On the other hand, if you want to make an adjacency matrix representation, you would instead create an array of bools and indicate which vertices have edges between them:

bool edges_as_matrix[vertices.size()][vertices.size()]; // `vector` is better
// edges_as_matrix[i][j] = true if there's an edge

(For this you would need a way to enumerate the vertices. In an undirected graph, the adjacency matrix is symmetric; in a directed graph it need not be.)

The list representation is better if there are few edges, while the matrix representation is better if there are a lot of edges.