What Is Better, Adjacency Lists or Adjacency Matrices for Graph Problems in C++?
What Is Better, Adjacency Lists or Adjacency Matrix, for Graph Problems in C++? What Are the Advantages and Disadvantages of Each? 6 11 Answers It Depends on...
What is better, adjacency lists or adjacency matrix, for graph problems in C++? What are the advantages and disadvantages of each?
11 Answers
It depends on the problem.
- Uses O(n^2) memory
- It is fast to lookup and check for presence or absence of a specific edge
between any two nodes O(1) - It is slow to iterate over all edges
- It is slow to add/delete a node; a complex operation O(n^2)
- It is fast to add a new edge O(1)
- Memory usage depends more on the number of edges (and less on the number of nodes),
which might save a lot of memory if the adjacency matrix is sparse - Finding the presence or absence of specific edge between any two nodes
is slightly slower than with the matrix O(k); where k is the number of neighbors nodes - It is fast to iterate over all edges because you can access any node neighbors directly
- It is fast to add/delete a node; easier than the matrix representation
- It fast to add a new edge O(1)
This answer is not just for C++ since everything mentioned is about the data structures themselves, regardless of language. And, my answer is assuming that you know the basic structure of adjacency lists and matrices.
Must Read
Memory
If memory is your primary concern you can follow this formula for a simple graph that allows loops:
An adjacency matrix occupies n2/8 byte space (one bit per entry).
An adjacency list occupies 8e space, where e is the number of edges (32bit computer).
If we define the density of the graph as d = e/n2 (number of edges divided by the maximum number of edges), we can find the "breakpoint" where a list takes up more memory than a matrix:
8e > n2/8 when d > 1/64
So with these numbers (still 32-bit specific) the breakpoint lands at 1/64. If the density (e/n2) is bigger than 1/64, then a matrix is preferable if you want to save memory.
You can read about this at wikipedia (article on adjacency matrices) and a lot of other sites.
Side note: One can improve the space-efficiency of the adjacency matrix by using a hash table where the keys are pairs of vertices (undirected only).