# Prim's Algorithm MST implementation in Python

• prims/
• Given module calculates the minimum spanning tree for a graph using Prim's algorithm. This algorithm is implemented using heapq module.

-->Description of Graph class :- The graph class of creates an adjacency list.

Description of addEdge(self,u,v,w):- This method stores the new vertices and edges, where u and v are the starting and ending vertices and w is the weight of the edges between these vertices.

Description of method prims(g) :- This method takes argument as g which is our graph, and then uses the prims algorithm to find the minimum spanning tree for the graph.

This algorithm is implemented using heap. The time complexity of this algorithm is O(v log e), where v is the number of vertices and e is the number of edges.

-->How to use the packet.

Import the prims module to your program

1) Enter the value of u,v, and w

2) Pass the value of u,v and w into the method addEdge and call the prims method, it will find the minimum spanning tree of the graph class.

Code

from heapq import *
import sys

class Graph:
""" graph class """
def __init__(self,v):
self.v=v

def __str__(self):
g='''Graph(\n'''
g+=")"
return g

def prims(g):
active_edges=[]

cost=0
heappush(active_edges,[0,1])

while len(active_edges)!=0:
wt,node=heappop(active_edges)

if mst[node]:
continue

mst[node]=True
cost+=wt

if not mst[v]:
heappush(active_edges,[w,v])
return cost

Output 