Question

def prim(G): Use Prims algorithm to find a MST for the graph G … # Initialize tree T with a single vertex and no edges v = n

need help filling in the code

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Since you have not provided the implementation of G (What does G represent here), I have assumed that G consists of an adjacency matrix and a function to get the number of vertices in the graph.

CODE

def prims(G):

# arbitrarily choose initial vertex from graph

vertex = 0

# initialize empty edges array and empty MST

MST = []

edges = []

visited = []

minEdge = [None,None,float('inf')]

V = G.getVertexCount()

# run prims algorithm until we create an MST

# that contains every vertex from the graph

while len(MST) != V-1:

# mark this vertex as visited

visited.append(vertex)

# add each edge to list of potential edges

for r in range(0, V):

if G.adjMatrix[vertex][r] != 0:

edges.append([vertex,r,G.adjMatrix[vertex][r]])

# find edge with the smallest weight to a vertex

# that has not yet been visited

for e in range(0, len(edges)):

if edges[e][2] < minEdge[2] and edges[e][1] not in visited:

minEdge = edges[e]

# remove min weight edge from list of edges

edges.remove(minEdge)

# push min edge to MST

MST.append(minEdge)

# start at new vertex and reset min edge

vertex = minEdge[1]

minEdge = [None,None,float('inf')]

return MST

1 def prims (G): # arbit rarily choose initial vertex from graph vertex0 4 # initialize empty edges array and empty MST MST [

Add a comment
Know the answer?
Add Answer to:
need help filling in the code def prim(G): Use Prim's algorithm to find a MST for the graph G … # Initialize tree T with a single vertex and no edges v = next(iter( )) # while the vertex set of T...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT