What is the difference between an adjacency matrix and an adjacency list?

Data Structures Questions



62 Short 41 Medium 47 Long Answer Questions Question Index

What is the difference between an adjacency matrix and an adjacency list?

The main difference between an adjacency matrix and an adjacency list lies in the way they represent the connections between vertices in a graph.

An adjacency matrix is a 2D matrix where each cell represents the presence or absence of an edge between two vertices. It is typically implemented using a 2D array. If there is an edge between vertex i and vertex j, the cell at position (i, j) will have a value of 1 or a weight value if the graph is weighted. If there is no edge, the cell will have a value of 0. This representation is useful for dense graphs where the number of edges is close to the maximum possible.

On the other hand, an adjacency list is a collection of linked lists or arrays where each vertex has a list of its adjacent vertices. It is typically implemented using an array or a hash table. Each vertex in the graph has a list that contains the vertices it is connected to. This representation is useful for sparse graphs where the number of edges is significantly smaller than the maximum possible.

In summary, the adjacency matrix provides a compact representation of the graph but requires more space for dense graphs, while the adjacency list provides a more efficient representation for sparse graphs but requires more space for dense graphs.