Skip to main content

Prim's Algorithm

Definition​

Prim's Algorithm is a greedy algorithm used to find the minimum spanning tree of a connected, undirected graph. It operates by selecting the smallest edge connected to the current minimum spanning tree and adding it to the tree, repeating this process until all vertices are included

Practice​

Prim(Graph, start_vertex):
initialize an empty set called MST (minimum spanning tree)
initialize a priority queue called pq
initialize a boolean array called visited to track visited vertices
add start_vertex to pq with priority 0
while pq is not empty:
vertex = pq.extract_min()
if vertex is not visited:
add vertex to MST
mark vertex as visited
for each neighbor of vertex:
if neighbor is not visited:
add edge(vertex, neighbor) to pq with priority equal to edge weight
return MST