Prim`s Algorithm

Given a weighted graph, many times we are interested in finding a minimum spanning tree (MST) for that graph. Prim's algorithm is a greedy method which does just this. A spanning tree is a subset of the edges of a graph that connects to every vertex, but contains no cycles. This spanning tree is called a minimum spanning tree if in addition the sum of the weights of the edges included in this tree is less than or equal to the sum of the weights of the edges of any other spanning tree for this graph.

Prim's algorithm works by building an initial tree and continuously growing the tree by adding the edge of least cost that will keep it as a tree. It can be explained with the following procedure.

1. Let *Tree _{v}* be the set of vertices included in the tree, and

*Tree*be the set of edges included in the tree. Initially

_{E}*Tree*and

_{V}*Tree*are empty.

_{E}2. Add an arbitrary vertex to

*Tree*(

_{V}*Tree*is still empty).

_{E}3. Find the edge

*e*of minimum weight such that one vertex is in

*Tree*and vertex is not in

_{V}*Tree*. Add the associated vertex to

_{V}*Tree*, and add

_{V}*e*to

*Tree*.

_{E}4. If edge was found in step 3, goto 5, else go to 6.

5. If the number of vertices in

*Tree*is less than the number of vertices in the original graph, then the graph is not connected and thus does not contain a minimum spanning tree. Goto 8.

_{V}6 If the number of vertices in

*Tree*is less than the number of vertices in the original graph, go to 2, else go to 7.

_{V}7. Output "The Minimum Spanning Tree is ",

*Tree*.

_{E}8. Output "This graph does not have a minimum spanning tree because it is not connected. "