ABSTRACT
Choosing how to store a graph in memory is a trade-off between space and speed. Depending on whether a graph is dense (many edges) or sparse (few edges), we use either an Adjacency Matrix or an Adjacency List to optimize our algorithms.
1. Density and Sparsity
To choose the right representation, we compare the number of edges to the maximum possible edges.
-
Maximum Edges: In a graph with vertices, if every vertex connects to every other vertex (including itself), .
-
Dense Graph: is close to .

- Sparse Graph: is significantly smaller than .

2. The Adjacency Matrix
An Adjacency Matrix is a 2D array of size .

- Logic: The cell at contains a
1if there is an edge from vertex to vertex , and a0otherwise. - Weights: For weighted graphs, replace the
1s with the actual edge costs (e.g., ). - Space Complexity: .
How would the adjacency matrix of an undirected graph look like?
STOP and Think Answer: The adjacency matrix of an undirected graph is always symmetric across the diagonal (). This is because an edge between and works in both directions.
3. The Adjacency List
An Adjacency List uses an array of lists. Each index in the array corresponds to a vertex, and the list at that index contains its neighbors.

- Logic: If vertex connects to and , the list at
index 0is[1, 4]. - Weights: Store neighbors as pairs:
(destination, weight). - Space Complexity: .
4. Representation Comparison
| Feature | Adjacency Matrix | Adjacency List |
|---|---|---|
| Best For | Dense Graphs | Sparse Graphs |
| Space | ||
| Edge Lookup | (Very Fast) | |
| Find all Neighbors | ||
| Add Vertex | ||
| Weighted Version | Replace s with weights | Store pairs (neighbor, weight) |
5. Summary of Trade-offs
-
Matrices are great when you need to know instantly if an edge exists between two nodes, but they waste a massive amount of memory on
0s if the graph is sparse. -
Lists are the industry standard for most real-world applications (like web maps) because most real-world graphs are sparse.