Prim’s MST algorithm:
After selecting the starting vertex (node), select a vertex connected by a minimum cost edge among edges adjacent to the vertex. After that, the minimum spanning tree is expanded by selecting a vertex connected from that vertex to the minimum edge again.
This is my code:
INF=9999
def getMinVertex(dist,selected):
minv=-1
mindist=INF
for v in range(len(dist)):
if not selected[v] and dist[v]<mindist:
mindist=dist[v]
minv=v
return minv
def MSTPrim(vertex,adj):
vsize=len(vertex)
dist=[INF]*vsize
dist[0]=0
selected=[False]*vsize
for i in range(vsize):
u=getMinVertex(dist,selected)
selected[u]=True
print(vertex[u],end=':')
print(dist)
for v in range(vsize):
if (adj[u][v] !=None):
if selected[v]==False and adj[u][v]<dist[v]:
dist[v]=adj[u][v]
vertex=['A','B','C','D','E','F','G']
weight = [
[None, 29, None, None, None, 10, None],
[29, None, 16, None, None, None, 15],
[None, 16, None, 12, None, None, None],
[None, None, 12, None, 22, None, 18],
[None, None, None, 22, None, 27, 25],
[10, None, None, None, 27, None, None],
[None, 15, None, 18, 25, None, None]
]
print("MST By Prim's Algoirthm")
MSTPrim(vertex,weight)
And this is example code:
I don’t know why the two are getting different results.
Despite looking at the example and writing the same code, the desired result is not coming out.
Dhru Jdj is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.