Representing Graphs
Adjacency List & Matrix
Learn two fundamental ways to store and represent graphs in discrete math: the adjacency matrix and the adjacency list.
What Is a Graph?
A graph \( G = (V, E) \) is a structure consisting of a set of vertices (nodes) \( V \) and a set of edges \( E \) connecting pairs of vertices. Graphs model relationships: social networks, road maps, computer networks, and more.
Directed vs Undirected Graphs
Why Represent Graphs?
Before we can run algorithms on a graph (shortest path, connectivity, coloring), we need to store the graph in a computer's memory. The two most common representations are:
The Adjacency Matrix
For a graph \( G = (V, E) \) with \( n = |V| \) vertices, the adjacency matrix \( A \) is an \( n \times n \) matrix where:
Matrix Example: Undirected Graph
The Adjacency List
An adjacency list stores, for each vertex \( v \in V \), a list of all vertices adjacent to \( v \). This is typically an array of linked lists or dynamic arrays.
List Example: Same Graph
Matrix vs List: Key Distinction
| Adjacency Matrix | Adjacency List | |
|---|---|---|
| Space | \( O(|V|^2) \) | \( O(|V| + |E|) \) |
| Check edge \( (u,v) \) | \( O(1) \) | \( O(\deg(u)) \) |
| List all neighbors | \( O(|V|) \) | \( O(\deg(v)) \) |
| Add edge | \( O(1) \) | \( O(1) \) |
| Best for | Dense graphs | Sparse graphs |
How to Build a Representation
Example 1: Triangle Graph
Example 2: Directed Graph
Example 3: A Larger Undirected Graph
Reading Degree from Representations
The degree of vertex \( v \), written \( \deg(v) \), is the number of edges incident to \( v \).
Common Mistakes
Summary Comparison
| Property | Adjacency Matrix | Adjacency List |
|---|---|---|
| Space complexity | \( \Theta(V^2) \) | \( \Theta(V + E) \) |
| Edge lookup | \( O(1) \) | \( O(\deg(v)) \) |
| Iterate neighbors | \( O(V) \) | \( O(\deg(v)) \) |
| Undirected symmetry | Symmetric matrix | Both lists updated |
| Simple implementation | 2D array | Array of lists |
| Ideal use case | Dense, \( E \approx V^2 \) | Sparse, \( E \ll V^2 \) |
Question 1 of 5
What is the space complexity of an adjacency matrix for a graph with \( n \) vertices?
Question 2 of 5
In the adjacency matrix of an undirected graph, which property always holds?
Question 3 of 5
An undirected graph has \( 4 \) vertices and \( 5 \) edges. How many total entries appear across all adjacency lists?
Question 4 of 5
Which representation is more space-efficient for a sparse graph where \( |E| \ll |V|^2 \)?
Question 5 of 5
A directed graph has vertices \( \{1, 2, 3\} \) and edges \( (1, 2), (2, 3), (3, 1) \). What is \( A[2][1] \) in its adjacency matrix?