Representing Graphs
- There are two natural ways to represent a graph.
- But first some terms.
- A graph $G=(V,E)$ is dense if $|E| \approx |V|^2$
- A graph $G=(V,E)$ is sparse if $|E| \approx |V|$
- Why are these reasonable definitions?
- For a fully connected graph, or complete graph, every vertex is connected to every other vertex.
- Thus there are $|V|-1$ unique edges from the first vertex
- And there are $|V|-2$ unique edges from the second vertex (don't count the edge from the first to the second)
- ...
- $\sum_{i=1}^{|V|-1}i$ edges.
- So there are $O(n^2)$ edges in a complete graph.
- For a tree on the other hand we have seen that $|V|=|E|-1$.
- We have two different forms of representing graphs in code.
- An adjacency matrix is used to represent dense graphs
- This is a two dimensional matrix where
- the rows can represent connections from the first vertex u
- the columns can represent connections to the second vertex v
- The intersection represents the presence of an edge (u,v)
- If the graph is weighted, it is customary to store the weight
- If the graph is directed M[u,v] is not the same as M[v,u]
- This requires $O(|V|^2)$ space
- But checking for an edge is $O(1)$
- And checking all adjacent edges is $O(|V|)$
- An adjacency list is used to represent sparse graphs.
- Generally this is an array of lists.
- Each entry in the array represents adjacent vertexes to a given vertex.
- This is usually in the form of a linked list.
- In this case, it requires $(|V|+|E|)$ space (likely $2|E|$, but ...
- It requires at most $O(|V|)$ to check for an edge, but this is probably much lower (since it is sparse)
- It requires at most $O( \textrm{adj}(V))$ to find adjacencies.(just traverse the list)