Vennela - Tandra - 2403032010058 - Prims Algorithm
Vennela - Tandra - 2403032010058 - Prims Algorithm
Presented By:
Tandra Vennela
2403032010058
Prim's Algorithm
Prim's algorithm grows one SCC (X and S) as a single tree
• X (edges) and S (vertices) are the sets of intermediate edges and vertices in
this partial MST
• On each iteration, X grows by one edge, and S by one vertex
The smallest edge between a vertex in S and a vertex outside S (V - S)
All vertices S and V-1 edges must eventually move into S and X
Cannot create a cycle since new vertex not currently in S and we never add a new
edge between two nodes already in S
Prims Algorithm
What is an efficient data structure to retrieve that edge?
• The algorithm is basically Dijkstra's algorithm except that the PQ key value for
each node outside S is its smallest edge into S
2
Prim's Algorithm – An Intuitive Version
Consider each node as wanting to get into club S
All nodes must join the club before we finish
Each non-member (V-S) has an entry key which is the smallest edge
length from itself to any current member of the club
At each iteration the non-member with the smallest key (edge length)
joins the club
Whenever a new member joins the club, all non-members with edges
3
Prim's Algorithm
1 2
1 2 3 S = {5}
1:
∞
1 2
1 2 3 S = {5}
1:
∞
7
6
Prim’s Algorithm
deletemin returns node
with shortest edge into S
1 2
1 2 3 X: S = {5}
1:
{4,5} S = {4,5} ∞
7
7
Prim’s Algorithm
Don’t actually store S or X.
Final S is all V and we get MST using
prevs which are fixed once node dequeued.
PQ contains nodes not yet in MST (V – S)
1 2
1 2 3 X: S = {5}
1:
{4,5} S = {4,5} ∞
7
8
Prim’s Algorithm
Update then decreases keys in PQ
(shortest edge into S) where possible,
based on new node just added to S
1 2
1 2 3 X: S = {5}
1: 4
{4,5} S = {4,5} 2: 4
8
4 3
7
9
Prim’s Algorithm
8
4 3
7
10
Prim’s Algorithm
8
4 3
7
11
Prim’s Algorithm
7
12
Prim’s Algorithm
7
13
Prim’s Algorithm
• Punch-lines
• Prim’s with Array PQ is best for a dense graph
• Kruskal’s with sets OR Prim’s with Heap PQ are both about the same for
sparser graphs
• Kruskal’s gives more control when choosing between edges with ties in
cost and some consider Kruskal’s as easier to implement
15
THANK YOU