Representation
- Edge List
- Form a list of vertices
- Form a list of edges
- Each edge has a pointer to the two endpoints
- In a undirected graph, order doesn't matter, represent each edge once
- In a directed graph, first pointer points to start point, second pointer points to endpoint of the edge.
- Direct access from an edge to a vertex
- Bad access from a vertex to an edge
- Really bad for the operation Adjacent(u,v) which tells us if u and v are adjacent.
- Also bad for finding all of the incident edges of a vertex.
- Not really very good, we often need to find an edge from a vertex, not the other way around.
- O(|E|+|V|)
- Adjacency Lists
- Store vertices in an array
- Each has a list of adjacent edges
- This list is just the index to the vertex that is adjacent, plus perhaps the weight.
- Directed and undirected graphs, this is the same.
- To see if u is adjacent to v, search u's list for link to v
- To find all incident edges, just traverse the list.
- This is good for sparse graphs
- This is not good for "Which cities does Route 6 connect?"
- But we usually don't ask that.
- It is not good for dense, or fully connected graphs
- Because each edge is represented twice.
- O(|E|+|V|)
- Adjacency Matrix
- Form a matrix (or grid)
- Vertices for horizontal and vertical indices
- If there is a path from u to v, at Adj[u,v] put a 1
- Or the weight if we are talking about a weighted graph
- If it is an undirected graph, put a 1 (or the weight) at Adj[v,u]
- O(|V|2)