MST_Prim
MST_Prim
L13.2
Adjacency-matrix
representation
The adjacency matrix of a graph G = (V, E), where
V = {1, 2, …, n}, is the matrix A[1 . . n, 1 . . n]
given by
1 if (i, j) E,
A[i, j] =
0 if (i, j) E.
A 1 2 3 4
2 1 1 0 1 1 0 Q(V 2) storage
2 0 0 1 0 dense
3 4 3 0 0 0 0 representation.
4 0 0 1 0
L13.3
Adjacency-list representation
An adjacency list of a vertex v V is the list Adj[v]
of vertices adjacent to v.
2 1 Adj[1] = {2, 3}
Adj[2] = {3}
Adj[3] = {}
3 4 Adj[4] = {3}
For undirected graphs, | Adj[v] | = degree(v).
For digraphs, | Adj[v] | = out-degree(v).
Handshaking Lemma: vV = 2 | E | for undirected
graphs adjacency lists use Q(V + E) storage —
a sparse representation (for either type of graph).
L13.4
Minimum spanning trees
Input: A connected, undirected graph G = (V, E)
with weight function w : E R.
• For simplicity, assume that all edge weights are
distinct. (cormen book covers the general case.)
L13.5
Example of MST
6 12
5 9
14 7
8 15
3 10
L13.6
Prim’s algorithm
IDEA: Maintain V – A as a priority queue Q. Key
each vertex in Q with the weight of the least-
weight edge connecting it to a vertex in A.
QV
key[v] for all v V
key[s] 0 for some arbitrary s V
while Q
do u EXTRACT-MIN(Q)
for each v Adj[u]
do if v Q and w(u, v) < key[v]
then key[v] w(u, v) ⊳ DECREASE-KEY
p[v] u
At the end, {(v, p[v])} forms the MST.
L13.14
Example of Prim’s algorithm
A
6 12
V–A
5 9
14 7
8 15
0
3 10
L13.15
Example of Prim’s algorithm
A
6 12
V–A
5 9
14 7
8 15
0
3 10
L13.16
Example of Prim’s algorithm
A
6 12
V–A
5 9
7
14 7
8 15
0 15
3 10
10
L13.17
Example of Prim’s algorithm
A
6 12
V–A
5 9
7
14 7
8 15
0 15
3 10
10
L13.18
Example of Prim’s algorithm
A 12
6 12
V–A
5 9
5 7 9
14 7
8 15
0 15
3 10
10
L13.19
Example of Prim’s algorithm
A 12
6 12
V–A
5 9
5 7 9
14 7
8 15
0 15
3 10
10
L13.20
Example of Prim’s algorithm
A 6
6 12
V–A
5 9
5 7 9
14 7
8 15
14 0 15
3 10
8
L13.21
Example of Prim’s algorithm
A 6
6 12
V–A
5 9
5 7 9
14 7
8 15
14 0 15
3 10
8
L13.22
Example of Prim’s algorithm
A 6
6 12
V–A
5 9
5 7 9
14 7
8 15
14 0 15
3 10
8
L13.23
Example of Prim’s algorithm
A 6
6 12
V–A
5 9
5 7 9
14 7
8 15
3 0 15
3 10
8
L13.24
Example of Prim’s algorithm
A 6
6 12
V–A
5 9
5 7 9
14 7
8 15
3 0 15
3 10
8
L13.25
Example of Prim’s algorithm
A 6
6 12
V–A
5 9
5 7 9
14 7
8 15
3 0 15
3 10
8
L13.26
Example of Prim’s algorithm
A 6
6 12
V–A
5 9
5 7 9
14 7
8 15
3 0 15
3 10
8
L13.27