Prim and Dij
Prim and Dij
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 explores 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 algorithm is a greedy algorithm that starts from one vertex and continue to add the edges with the
smallest weight until the goal is reached. The steps to implement the prim's algorithm are given as follows
-
Now, let's see the working of prim's algorithm using an example. It will be easier to understand the prim's
algorithm using an example.
Step 1 - First, we have to choose a vertex from the above graph. Let's choose B.
Step 2 - Now, we have to choose and add the shortest edge from vertex B. There are two edges from
vertex B that are B to C with weight 10 and edge B to D with weight 4. Among the edges, the edge BD
has the minimum weight. So, add it to the MST.
Step 3 - Now, again, choose the edge with the minimum weight among all the other
edges. In this case, the edges DE and CD are such edges. Add them to MST and
explore the adjacent of C, i.e., E and A. So, select the edge DE and add it to the MST.
Step 4 - Now, select the edge CD, and add it to the MST.
Step 5 - Now, choose the edge CA. Here, we cannot select the edge CE as it would create a cycle to the
graph. So, choose the edge CA and add it to the MST.
So, the graph produced in step 5 is the minimum spanning tree of the given graph. The cost of the MST
is given below -
Algorithm
o Time Complexity
Data structure used for the minimum edge weight Time Complexity
The time complexity of Dijkstra's Algorithm is O(V2) with the help of the adjacency matrix
representation of the graph.
This time complexity can be reduced to O((V + E) log V) with the help of an adjacency list
representation of the graph, where V is the number of vertices and E is the number of edges in the
graph.
Steps Diagram
The set sptSet is initially empty and distances assigned
to vertices are {0, INF, INF, INF, INF, INF, INF, INF}
where INF indicates infinite.
Now pick the vertex with a minimum distance value.
The vertex 0 is picked, include it in sptSet .
So sptSet becomes {0}.
After including 0 to sptSet , update distance values of its
adjacent vertices.
Adjacent vertices of 0 are 1 and 7. The distance values of
1 and 7 are updated as 4 and 8.
Pick the vertex with minimum distance value and not
already included in SPT (not in sptSET ). The vertex 1
is picked and added to sptSet .
So sptSet now becomes {0, 1}. Update the distance
values of adjacent vertices of 1.
The distance value of vertex 2 becomes 12 .