Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a connected weighted undirected graph. This tutorial will guide you through the steps of implementing Prim's algorithm.
Steps of Prim's Algorithm
Initialize:
- Create a set
S
that will contain all the vertices included in the MST. - Create a set
Q
that will contain all the vertices not yet included in the MST. - Set all vertices in
Q
as their own parent. - Set all vertices in
Q
as having a distance of infinity from the MST. - Set the distance of the first vertex in
Q
to 0.
- Create a set
Select the vertex with the smallest distance:
- Select the vertex
u
inQ
with the smallest distance.
- Select the vertex
Add
u
toS
:- Add
u
toS
.
- Add
Update the distances:
- For each vertex
v
inQ
that is adjacent tou
:- If the distance of
v
throughu
is less than the current distance ofv
, update the distance ofv
to be the distance throughu
and setu
as the parent ofv
.
- If the distance of
- For each vertex
Repeat steps 2-4:
- Repeat steps 2-4 until all vertices in
Q
have been added toS
.
- Repeat steps 2-4 until all vertices in
Example
Here's an example of how Prim's algorithm works on a graph:
A -- 2 -- B
| |
5 1
| |
C -- 3 -- D
If we start with vertex A
, the MST will be A-B-C-D
.
Code Implementation
You can implement Prim's algorithm in various programming languages. Here's an example in Python:
def prims_algorithm(graph):
# Initialize MST and distances
mst = []
distances = {vertex: float('inf') for vertex in graph}
distances[0] = 0 # Start with vertex 0
while len(mst) < len(graph):
# Find the vertex with the smallest distance
u = min(distances, key=distances.get)
# Add the vertex to the MST
mst.append(u)
# Update the distances of the adjacent vertices
for v in graph[u]:
if distances[v] > distances[u] + graph[u][v]:
distances[v] = distances[u] + graph[u][v]
return mst
# Example graph
graph = {
0: {1: 2, 2: 5},
1: {0: 2, 2: 1, 3: 3},
2: {0: 5, 1: 1, 3: 3},
3: {1: 3, 2: 3}
}
# Run Prim's algorithm
mst = prims_algorithm(graph)
print("MST:", mst)
For more information on Prim's algorithm, you can read our in-depth article on the topic.
Prim's Algorithm Graph