Graph Representation
Notation
We will denote:
as a graph.
Sparse vs Dense Graphs
Review the concepts of sparse and dense graphs.
Real-world graphs are usually sparse. Keep this in mind when choosing a representation.
List of Edges
This is the least common and simplest way to represent a graph.
A graph is simply a list of edges
The edges look sorted in the above figure, but in reality, there is no sorting of edges. It really depends on how you add them to the list.
- Access to neighbors is expensive:
. - Inserting an edge is cheap:
. - Deleting an edge is also similarly expensive:
. - Space efficient for sparse graphs:
.
Summary:
- Desirable for really sparse graphs.
- Not very common in practice.
Adjacency List
Basically a dictionary where the keys are the vertices and the values are list of vertices that are neighbors.
- Access to outgoing edges is cheap:
- Hash table lookup of vertex
- Access to incoming edges is expensive:
- Go through all vertices and check if an edge exists
- Inserting an edge is cheap:
- Deleting an edge is expensive:
- To delete
, find and delete from the adjacency list of (and maybe from the adjacency list of in case of an undirected graph)
- To delete
- Space efficient for sparse graphs:
Summary:
- Good for sparse graphs, which is common in practice.
- Problems in practice require frequent access to neighbors, so a real advantage over list of edges.
Adjacency Matrix
Use a matrix of
Initially, all elements are set to a falsey value. If there is an edge between m[u][v]
to a truthy value.
- Access to neighbors:
, go throughm[u][v]
- Inserting an edge is cheap:
- Deleting an edge is cheap:
- Not space efficient, since it always reserves space for a complete graph:
Summary:
- Good for dense graphs.
Total Summary
- For sparse graphs, use adjacency list.
- For dense graphs, use adjacency matrix.
- List of edges is not very common in practice.
References: