f d a b c e g Prim’s Algorithm – an Example edge candidates choosen
f d a b c e g
f d a b c e g
f d a b c e g
f d a b c e g
f d a b c e g Total weight of the MST: 14
Prim’s Algorithm - Description MST-Prim(G, w) choose an arbitrary r V(G) Initialize T as a tree consisting of vertex r only. while T has < n vertices do let (u, v) be the lightest edge with u V(T) and v V(G) – V(T) T T { (u, v) } return T Correctness follows a previous corollary: Let A be a subset of E that is included in some MST of G, and C be a connected component in the forest G =. If (u, v) is a light edge connecting C to some other component in G, then (u, v) is safe for A.
Implementation At every iteration, maintain the following information for each vertex v in G: cost(v) is the weight of the lightest edge connecting v to T. closest(v) is the vertex y in T such that cost(v) = w(v, y). The next edge to add is (u, closest(u)). Here u is the vertex with minimum cost in V(G) – V(T). u closest(u) T cost(u)
Updating Closest Vertex u v z After adding (u, closest(u)), scan every neighbor v of u: set closest(v) = u if cost(v) decreases, update cost(v) if necessary. MST v u z new cost
Priority Queue Implementation MST-Prim(G, w) choose r V(G) for each u V(G) do cost(u) cost(r) 0 Q V(G) // Build a priority queue keyed by cost closest(r) NIL while Q { } do do u Extract-Min(Q) for each v Adj(u) do if v Q and w(u, v) < cost(v) then closest(v) u cost(v) w(u, v) // Decrease-Key
Running Time Analysis Queue opertions: Build-Queue creates the initial queue Extract-Min extracts the vertex of minimum cost Decrease-Key decreases cost(v) for v in Q, if necessary Heap (V) O(lg V) O(lg V) O(E lg V) #operations 1 V 2E Array (V) O(V) O(1) O(V ) 2 Q Build-Queue Extract-Min Decrease-Key Time Prim’s