CP164 Study Guide - Midterm Guide: Priority Queue
![](https://new-preview-html.oneclass.com/17vWDzZOJA5gQMkpKazojxyMEbRYVrnP/bg1.png)
Applying Prim's Algorithm
Prim's Algorithm Outline
• Initialize a priority queue.
• Start with an arbitrary node in the graph (base station, in this case).
• Insert all of the edges connected to the node into the priority queue (i.e. the tunnel costs).
• While we have not yet visited all the nodes, remove the first (cheapest) edge from the priority
queue. Add the node at the opposite end of that edge to our list of visited nodes. Now insert all of
the other edges from that node into the priority queue.
•
Solving this example would look like this:
Node Kept
Edge Removed
Priority Queue
A
A → B, 2
A → B, 2
A → C, 3
A → D, 7
B
A → C, 3
A → C, 3
A → D, 7
B → C, 6
B → G, 4
C
C → E, 1
A → D, 7
B → C, 6
B → G, 4
C → E, 1
C → F, 8
E
B → G, 4
A → D, 7
B → C, 6
B → G, 4
C → F, 8
E → D, 5
E → F, 4
G
G → F, 2
A → D, 7
B → C, 6
C → F, 8
E → D, 5
E → F, 4
G → F, 2
F
E → F, 4
A → D, 7
B → C, 6
C → F, 8
E → D, 5
E → F, 4
-
E → D, 5
A → D, 7
B → C, 6
C → F, 8
E → D, 5
D
A → D, 7
B → C, 6
C → F, 8
Note that when node E is added to the list of visited nodes, the edge from E → F (cost 4), is
added to the priority queue. It is eventually removed from the priority queue when the current
node is F because it has the lowest cost. However, both ends of this edge (E and F) are already in
the final node list, so this edge is discarded, and the next cheapest edge, E → D is used instead.
Document Summary
Initialize a priority queue: start with an arbitrary node in the graph (base station, in this case), while we have not yet visited all the nodes, remove the first (cheapest) edge from the priority. Insert all of the edges connected to the node into the priority queue (i. e. the tunnel costs). queue. Add the node at the opposite end of that edge to our list of visited nodes. Now insert all of the other edges from that node into the priority queue. A b, 2 a c, 3 a d, 7. A c, 3 a d, 7 b c, 6 b g, 4. A d, 7 b c, 6 b g, 4 c e, 1 c f, 8. A d, 7 b c, 6 b g, 4 c f, 8 e d, 5 e f, 4. A d, 7 b c, 6 c f, 8 e d, 5 e f, 4 g f, 2.