How to do it...

Follow these steps to implement Prim's algorithm:

  1. Choose any vertex from the graph as the root of the minimum spanning tree. It can be any random vertex.
  2. Find all of the edges from the vertex (or vertices in the tree) to other vertices in the graph. From those vertices, choose the vertex that has the edge with the minimum weight and add that vertex to the tree.
  3. Repeat step 2 until all the vertices of the graph are added to the minimum spanning tree.

Consider the following weighted graph:

Figure 10.29

Now, to get the minimum spanning tree of this graph, we connect the vertices starting from vertex a (you can consider any vertex ...

Get Practical C Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.