Graph Algorithms
Summarized notes on Introduction to Algorithms, Chapter 22
Representations of Graphs
- two standard ways to represent a graph
- adjacency list
- adjacency matrix
Adjacency List
- compact way to represent sparse graphs (when
) - array
is a map of lists, 1 for each vertex in - for each
, list contains all vertices , such that there is an edge contains all vertices adjacent to in
Properties
- if G is directed, sum of lengths of adjacency lists is
- if G is undirected, sum of lengths of adjacency lists is
- easy to store attributes, e.g. weight to include multiple attributes
- iterating over all edges is efficient
- issue: checking if
exists requires searching for in Adj[u] - less space efficient for dense graphs
- asymptotically at least equally space-efficient as a matrix
- more complex representation than matrix
Complexity
Bounds | |
---|---|
Space requirement | |
Time to list all vertices adjacent to |
|
Time to determine whether |
|
Edge weight lookup time |
Adjacency Matrix
- Assume named vertices
representation is matrix is in matrix if , and 0 otherwise- Good for representing dense graphs where
close to
Properties
- edge weight maybe stored as value at
and store null if edge does not exist - storing multiple attributes maybe hard; depends on implementation
- easy to check if
exists - for undirected graph the matrix is symmetric (graph is its own transpose) → potential to reduce space requirement almost in half based on this symmetry
- require only 1 bit ber entry
- simplest graph representation
- value 1 at center diagonal (top left → bottom right) indicates a cycle in the graph
Complexity
Bounds | |
---|---|
Space requirement (independent of number of edges) | |
Iterating all edges | |
Time to determine whether |
|
Edge weight lookup time |