Adjacency lists are a popular way to represent graphs in algorithmic design. Each node in the graph is assigned an adjacency list that consists of nodes to which there is an edge from .

Adjacency lists for directed graphs can be stored as an array of vectors: vector<int> adj[N], where N is a constant denoting the number of nodes in the graph.

vector<int> adj[N];
adj[1].push_back(2);
// etc.

For an undirected graph, each edge is added in both directions. For a weighted graph, we can extend the structure with the following, where the second int in the pair is the weight associated with the edge from node to .

vector<pair<int, int>> adj[N];

Implications

The benefit of using adjacency lists is that we can efficiently find the nodes to which we can move from a given node through an edge. For example, we can use a simple iterator-based loop through a node ‘s adjacency list.

List representations are ideal if is much less than , i.e., if the graph is sparse.

See also