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 1 if there is an edge from vertex to vertex , and a 0 otherwise.
  • Weights: For weighted graphs, replace the 1s with the actual edge costs (e.g., ).
  • Space Complexity: .

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 0 is [1, 4].
  • Weights: Store neighbors as pairs: (destination, weight).
  • Space Complexity: .

4. Representation Comparison

FeatureAdjacency MatrixAdjacency List
Best ForDense GraphsSparse Graphs
Space
Edge Lookup (Very Fast)
Find all Neighbors
Add Vertex
Weighted VersionReplace s with weightsStore 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.