# Prims algorithm

The graph is:. Following is an example of a spanning tree for the above graph. Please note that only the highlighted edges are included in the spanning tree. Figure 3. Also, there can be multiple spanning trees possible for any given graph. For eg: In addition to the spanning tree in the above diagram, the graph can also have another spanning tree as shown below:. Figure 4. Hence, the total number of spanning trees S for the given graph second diagram from top can be computed as follows:. The cost of a spanning tree is the total of the weights of all the edges in the tree.

For example, the cost of spanning tree in Fig. Since we can have multiple spanning trees for a graph, each having its own cost value, the objective is to find the spanning tree with minimum cost. Note : There can be multiple minimum spanning trees for a graph, if any two edges in the graph have the same weight.

However, if each edge has a distinct weight, then there will be only one minimum spanning tree for any given graph. Given a weighted, undirected and connected graph Gthe objective is to find the minimum spanning tree G' for G.

Apart from the Prim's Algorithm for minimum spanning tree, we also have Kruskal's Algorithm for finding minimum spanning tree.

However, this tutorial will only discuss the fundamentals of Prim's Algorithm. Since this algorithm aims to find the spanning tree with minimum cost, it uses greedy approach for finding the solution.

As part of finding the or creating the minimum spanning tree fram a given graph we will be following these steps:. Step 1 : Keep a track of all the vertices that have been visited and added to the spanning tree.

Step 3 : Choose a random vertexand add it to the spanning tree. This becomes the root node. Step 4 : Add a new vertex, say xsuch that x is not in the already built spanning tree.

Thus, x can be adjacent to any of the nodes that have already been added in the spanning tree. Adding x to the spanning tree should not form cycles. Step 5 : Repeat the Step 4, till all the vertices of the graph are added to the spanning tree. Let's try to trace the above algorithm for finding the Minimum Spanning Tree for the graph in Fig. Figure 5: Initial arrays when tree is empty. Figure 6: Setting key value of root node.

Figure 8: visited array after adding the root node.

Figure 9: key array after adding the root node. Note : There will be no change in the parent[] because f is the root node. Figure parent array after adding the root node. The arrays key[] and visited[] will be searched for finding the next vertex. Figure Adding vertex c. Figure visited array after adding vertex c. Figure key array after adding the root node. Figure Adding vertex a.It starts with an empty spanning tree.

The idea is to maintain two sets of vertices. The first set contains the vertices already included in the MST, the other set contains the vertices not yet included. At every step, it considers all the edges that connect the two sets, and picks the minimum weight edge from these edges. After picking the edge, it moves the other endpoint of the edge to the set containing MST.

Assign key value as 0 for the first vertex so that it is picked first. To update the key values, iterate through all adjacent vertices. For every adjacent vertex vif weight of edge u-v is less than the previous key value of vupdate the key value as weight of u-v.

The idea of using key values is to pick the minimum weight edge from cut. The key values are used only for vertices which are not yet included in MST, the key value for these vertices indicate the minimum weight edges connecting them to the set of vertices included in MST.

Let us understand with the following example:. Now pick the vertex with minimum key value. The vertex 0 is picked, include it in mstSet. After including to mstSetupdate key values of adjacent vertices. Adjacent vertices of 0 are 1 and 7. The key values of 1 and 7 are updated as 4 and 8. Following subgraph shows vertices and their key values, only the vertices with finite key values are shown.

The vertices included in MST are shown in green color. The vertex 1 is picked and added to mstSet. Update the key values of adjacent vertices of 1. The key value of vertex 2 becomes 8. We can either pick vertex 7 or vertex 2, let vertex 7 is picked.

Update the key values of adjacent vertices of 7. The key value of vertex 6 and 8 becomes finite 1 and 7 respectively. Vertex 6 is picked.

Update the key values of adjacent vertices of 6.

The key value of vertex 5 and 8 are updated. We repeat the above steps until mstSet includes all vertices of given graph. Finally, we get the following graph. How to implement the above algorithm? We use a boolean array mstSet[] to represent the set of vertices included in MST.

If a value mstSet[v] is true, then vertex v is included in MST, otherwise not.Like Kruskal's algorithm, Prim's algorithm is also used to find the minimum spanning tree from a graph and it also uses greedy technique to do so.

In prim's algorithm, we start growing a spanning tree from the starting position and then further grow the tree with each step. We divide the vertices into two parts, one contains the vertices which are in the growing tree and the other part has the rest of the vertices.

We mark the vertices which are in the growing tree differently to the vertices which are not in it as we have used different colors in the above picture. This helps us to avoid loops in the tree. Now, we select the light edge each time and put the vertex at the end of the light edge into the growing tree. As we have already discussed that a light edge is a must have edge in a MST, so selecting a light edge every time gives us a minimum spanning tree. We are going to use a minimum priority queue to store all the unvisited nodes.

The reason for using the min-queue will be clear after going through the steps of the algorithm. Initially, none of the nodes are visited. So, we put all the nodes in the queue with a key value of infinity for each node, except the node we are going to start our tree, we will make its key 0.

We can arbitrarily choose any node to start with. Since each node has a key of infinity except the node with which we are starting, so dequeuing the minimum priority queue will give us that node because its value of the key is minimum.

Now, we will visit each adjacent node of this node and change the key of each adjacent node to the weight of the edges going to them. So, now dequeue will give us the node with the edge with minimum weight and that's why we are using a minimum priority queue. Also we are dequeuing the queue in every step, so only the unvisited node will be in the queue. Now, we will visit the adjacent nodes of this node and assign key equal to the weights of the edges to them.

If the node has already a key assigned to it, we will select the minimum key among the two. From the steps given above, it must be clear that our first task is to make the key of each node infinite except the node with which we are starting make it 0 and put them in a minimum priority queue.

We also need to keep the track of the nodes or the edges we are selecting in each step. We can either make a queue and put these nodes in that in the sequence we are selecting them and return at the last or we can keep the record of the parent of each node to trace back the MST. The for loop is checking all the adjacent nodes of u, and so we will first check if the node is in queue or not.

If it is not, then the node has already been taken and taking it again will make a loop.

**6.5 Prim's Algorithm for Minimum Spanning Tree - Data structures**

We will also compare the key already assigned to the node with the key of the current edge going to it and assign least of these two. We are going to do this analysis assuming that the minimum priority queue is implemented using a binary heap.This means it finds a subset of the edges that forms a tree that includes every vertexwhere the total weight of all the edges in the tree is minimized.

The algorithm operates by building this tree one vertex at a time, from an arbitrary starting vertex, at each step adding the cheapest possible connection from the tree to another vertex. Prim in [2] and Edsger W. Dijkstra in However, running Prim's algorithm separately for each connected component of the graph, it can also be used to find the minimum spanning forest.

In more detail, it may be implemented following the pseudocode below. As described above, the starting vertex for the algorithm will be chosen arbitrarily, because the first iteration of the main loop of the algorithm will have a set of vertices in Q that all have equal weights, and the algorithm will automatically start a new tree in F when it completes a spanning tree of each connected component of the input graph.

The algorithm may be modified to start with any particular vertex s by setting C [ s ] to be a number smaller than the other values of C for instance, zeroand it may be modified to only find a single spanning tree rather than an entire spanning forest matching more closely the informal description by stopping whenever it encounters another vertex flagged as having no associated edge. Different variations of the algorithm differ from each other in how the set Q is implemented: as a simple linked list or array of vertices, or as a more complicated priority queue data structure.

This choice leads to differences in the time complexity of the algorithm. In general, a priority queue will be quicker at finding the vertex v with minimum cost, but will entail more expensive updates when the value of C [ w ] changes.

The time complexity of Prim's algorithm depends on the data structures used for the graph and for ordering the edges by weight, which can be done using a priority queue. The following table shows the typical choices:.

A simple implementation of Prim's, using an adjacency matrix or an adjacency list graph representation and linearly searching an array of weights to find the minimum weight edge to add, requires O V 2 running time. However, this running time can be greatly improved further by using heaps to implement finding minimum weight edges in the algorithm's inner loop.

A first improved version uses a heap to store all edges of the input graph, ordered by their weight. This leads to an O E log E worst-case running time. But storing vertices instead of edges can improve it still further. The heap should order the vertices by the smallest edge-weight that connects them to any vertex in the partially constructed minimum spanning tree MST or infinity if no such edge exists.

Every time a vertex v is chosen and added to the MST, a decrease-key operation is performed on all vertices w outside the partial MST such that v is connected to wsetting the key to the minimum of its previous value and the edge cost of vw. Using a simple binary heap data structure, Prim's algorithm can now be shown to run in time O E log V where E is the number of edges and V is the number of vertices.

Let P be a connected, weighted graph. At every iteration of Prim's algorithm, an edge must be found that connects a vertex in a subgraph to a vertex outside the subgraph.

## Prim’s Minimum Spanning Tree Implementation

Since P is connected, there will always be a path to every vertex. The output Y of Prim's algorithm is a treebecause the edge and vertex added to tree Y are connected. Let Y 1 be a minimum spanning tree of graph P. Otherwise, let e be the first edge added during the construction of tree Y that is not in tree Y 1and V be the set of vertices connected by the edges added before edge e.

Then one endpoint of edge e is in set V and the other is not. Since tree Y 1 is a spanning tree of graph Pthere is a path in tree Y 1 joining the two endpoints. As one travels along the path, one must encounter an edge f joining a vertex in set V to one that is not in set V. Now, at the iteration when edge e was added to tree Yedge f could also have been added and it would be added instead of edge e if its weight was less than eand since edge f was not added, we conclude that.In this case, we start with single edge of graph and we add edges to it and finally we get minimum cost tree.

In this case, as well, we have n-1 edges when number of nodes in graph are n.

## Minimum Spanning Tree

This algorithm creates spanning tree with minimum weight from a given weighted graph. Each of this loop has a complexity of O n. After first initialization,parent is set from G[0][0] to G[0][v].

Since it is undirected graph we have to set equal values in both direction for [u][v] and [v][u]. After visting vertex 0,do the same for n-2 non visited vertices. Please explain what are we storing in visited,distance and from arrays…. An allover better explanation will definitely help very much.

Why is it necessary for every student to learn this algorithm when its already available on internet???? This is not the code for Prims, for prims it is necessary to be able to pick the node from where you start.

Also Prims doesnt need the union find datastructure which seems you implemented with the part where you set the parent from G[0][0] to G[0][v] after first initialization. This is just another implementation of Kruskal where you start with the lowest edge. This may cause some confusion. Your email address will not be published.

Begin Create edge list of given graph, with their weights. Draw all nodes to create skeleton for spanning tree. Select an edge with lowest weight and add it to skeleton and delete edge from edge list. Add other edges. While adding an edge take care that the one end of the edge should always be in the skeleton tree and its cost should be minimum.

Repeat step 5 until n-1 edges are added. Enter no. Leave a Reply Cancel reply Your email address will not be published.It shares a similarity with the shortest path first algorithm.

Having a small introduction about the spanning trees, Spanning trees are the subset of Graph having all vertices covered with the minimum number of possible edges.

They are not cyclic and cannot be disconnected. A connected Graph can have more than one spanning tree. So the major approach for the prims algorithm is finding the minimum spanning tree by the shortest path first algorithm. Basically this algorithm treats the node as a single tree and keeps on adding new nodes from the Graph. So it starts with an empty spanning tree, maintaining two sets of vertices, the first one that is already added with the tree and the other one yet to be included. So it considers all the edge connecting that value that is in MST and picks up the minimum weighted value from that edge, moving it to another endpoint for the same operation.

The distance of other vertex from vertex 1 are 8 for vertex 55 for vertex 6 and 10 for vertex 2 respectively. So the minimum distance i. Now the distance of other vertex from vertex 6 are 6 for vertex 43 for vertex 3 and 6 for vertex 2 respectively. Iteration 3 in the figure. Since distance 5 and 3 are taken up for making the MST before so we will move to 6 Vertex 4which is the minimum distance for making the spanning tree.

Since 6 is considered above in step 4 for making MST. So 10 will be taken as the minimum distance for consideration. Since all the vertices are included in the MST so that it completes the spanning tree with the prims algorithm.

Min heap operation is used that decided the minimum element value taking of O logV time. So the merger of both will give the time complexity as O Elogv as the time complexity.

So from the above article, we checked how prims algorithm uses the GReddy approach to create the minimum spanning tree. Also, we analyzed how the min-heap is chosen and the tree is formed. The time complexity for this algorithm has also been discussed and how this algorithm is achieved we saw that too. You can also go through our other related articles to learn more —. Forgot Password? Popular Course in this category. Course Price View Course. Free Data Science Course. By continuing above step, you agree to our Terms of Use and Privacy Policy.

Login details for this Free course will be emailed to you. Please provide your Email ID. Email ID is incorrect.Prim's Algorithm is used to find the minimum spanning tree from a graph. Prim's algorithm finds the subset of edges that includes every vertex of the graph such that the sum of the weights of the edges can be minimized. Prim's algorithm starts with the single node and explore all the adjacent nodes with all the connecting edges at every step.

The edges with the minimal weights causing no cycles in the graph got selected.

### Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5

Construct a minimum spanning tree of the graph given in the following figure by using prim's algorithm. The graph produces in the step 4 is the minimum spanning tree of the graph shown in the above figure. JavaTpoint offers too many high quality services. Mail us on hr javatpoint. Please mail your requirement at hr javatpoint. Duration: 1 week to 2 week. DS Tutorial. DS Array 2D Array. Linear Search Binary Search. Next Topic Kruskal's Algorithm.

Spring Boot. Selenium Py. Verbal A. Angular 7.

Compiler D. Software E.

## thoughts on “Prims algorithm”