Graphs and their representations
Define vertices, edges, directed and weighted graphs and degree, and store one graph as an adjacency list and as an adjacency matrix, comparing their space and time.
It opens on
Our graph has five vertices and its degrees, the number of edges at each vertex, are 2, 3, 3, 2 and 2. How many edges does it have, 12 or 6?
Why it matters
Graphs model road maps, networks, web links, course prerequisites and social connections, and every graph algorithm starts by choosing how to store the graph; the list-versus-matrix trade-off is asked in every data structures course.
Good to know first
- Binary trees: nodes joined by edges, a tree with n nodes has n − 1 edges
- Dictionaries: a key mapped to a value, looked up in O(1) on average
- Big-O, Big-Omega and Big-Theta: O(V), O(V²) and O(V + E) compared
Step by step
Vertices, edges and degree
Name a graph's vertices and edges, give each vertex's degree, and use the fact that the degrees add up to twice the number of edges.
The degree of a vertex is the number of edges at it. A has 2, B has 3, C has 3, D has 2 and E has 2.
neighbours and degrees
A common mix-up
The number of edges is the sum of the degrees.
In fact: Each edge is counted at both its ends, so the sum is twice the number of edges.
Two representations
Store the graph as an adjacency list and as an adjacency matrix, and compare their space and the time of common questions.
adj["B"] printed ['A', 'C', 'D'], B's neighbours, and its length is B's degree, 3. The lists hold 12 entries in all, 2E.
A common mix-up
An adjacency matrix is always better because edge lookups are O(1).
In fact: It needs V² cells whatever E is, and listing neighbours costs O(V), so for sparse graphs the list wins.
Directed and weighted graphs
Store a directed graph, giving in-degree and out-degree, and a weighted graph with a weight on each edge.
The run counted the out-degrees 2, 1, 1, 0, 0 and the in-degrees 0, 1, 1, 1, 1. They add to 4 each, the number of edges, since every edge has one tail and one head.
in and out degrees
A common mix-up
A directed edge u → v also lets you go from v to u.
In fact: Only u's list holds v; going back needs its own edge v → u.
Try it
A graph has degrees 1, 2, 2, 3 and 4. How many edges does it have?Answer
6, since the degrees add to 12
Hint: Halve the sum
Add the edge A–E. Which list entries and matrix cells change?Answer
Adj["A"] gains E and adj["E"] gains A; cells row A column E and row E column A become 1
Hint: Both ends
Add the prerequisite algo → os. What are os's in-degree and algo's out-degree now?Answer
2 and 1
Hint: One arrow leaves algo and arrives at os
Is there an edge B–E, and how does each representation answer?Answer
No; the matrix reads one cell, row B column E, which is 0; the list scans B's list, A, C, D, and does not find E.
What are the out-degree and the in-degree of intro?Answer
Out-degree 2, its edges to ds and org; in-degree 0, since no course leads to it.
