Graphs: Definitions and Implementation
Announcements
Today: Graphs, continued

Graph (V,E):
V: student PA3 submissions
E: \((u,v)\) if \(u\) is similar to \(v\)
Aux: vertex labelled by term
Sparse Graph:
\(|E| = O(|V|)\)

Graph (V,E):
V: ___________________
E: ___________________
Directed Graph:
each edge \((u,v)\) is ordered: \((u,v) \neq (v,u)\).
Howe (↓) and Seymour (↑) make this directed.
Weighted Graph:
each edge carries a weight \(w(u,v)\):
here, travel time in minutes.
In/Out-degree(v):
# edges directed into / out of \(v\).
Fastest route:
Seymour & Georgia → Burrard & Helmcken?

\(G = (V,E) \qquad |V| = n \qquad |E| = m\)
Running times are often reported in terms of \(n\),
the number of vertices, but they often depend
on \(m\), the number of edges.
Suppose \(n = 100\) vertices…
Give a lower bound on \(|E|\): ______
Give an upper bound on \(|E|\): ______

\(G = (V,E) \qquad |V| = n \qquad |E| = m\)
There are 28 vertices,
and every vertex has degree 3.
How many edges?
In general:
You each have a graph. Do these three things:
Try to trace every edge exactly once without lifting your pencil.
Come up with a rule that tells you if a trace is possible.
Devise an algorithm that will find a trace if it exists.

How do we get from here to there?
Need:
1. Common Vocabulary
2. Graph implementation
3. Traversal
4. Algorithms.
Data:
Functions (a few of them):
insertVertex(v)
removeVertex(v)
insertEdge(v, w)
removeEdge(v, w)
incidentEdges(v)
areAdjacent(v, w)
\(n\) vertices, \(m\) edges. Simple graphs by default.
| u | v | w | z | |
|---|---|---|---|---|
| u | a | c | ||
| v | a | b | ||
| w | c | b | d | |
| z | d |
An \(n \times n\) table. Cell \((v,w)\) holds the edge
between \(v\) and \(w\), or is empty.
Space: ______
insertVertex(v) ______
removeVertex(v) ______
incidentEdges(v) ______
areAdjacent(v, w) ______
Each vertex keeps a list of its incident edges.
Each edge knows its two endpoints, and
where it sits in both of their lists.
Space: ______
insertVertex(v) ______
removeVertex(v) ______
incidentEdges(v) ______
areAdjacent(v, w) ______
| Adj Matrix | Adj List | |
|---|---|---|
| Space | \(n^2\) | \(n + m\) |
insertVertex(v) |
\(n\)* | \(1\) |
removeVertex(v) |
\(n\)* | \(\deg(v)\) |
insertEdge(v, w) |
\(1\) | \(1\) |
removeEdge(v, w) |
\(1\) | \(\min(\deg(v), \deg(w))\) |
incidentEdges(v) |
\(n\) | \(\deg(v)\) |
areAdjacent(v, w) |
\(1\) | \(\min(\deg(v), \deg(w))\) |
* amortized: the matrix has room to grow, like a dynamic array.
Sparse graph: \(m = O(n)\)
Suppose \(n = 10^6\) vertices,
each with about 10 neighbours.
Matrix cells: ______
List entries: ______
Dense graph: \(m = \Theta(n^2)\)
Space: ______ vs ______
Most graphs we meet are sparse.
The adjacency list is the usual choice.
Next: traversal. How long does it take to visit every vertex and edge?
CPSC 221