Professional Documents
Culture Documents
61 Practical 05
61 Practical 05
Theory:
Prim's algorithm is a greedy algorithm used to find the minimum spanning tree
(MST) for a connected, undirected graph. The minimum spanning tree is a subset of
the edges of the graph that forms a tree that includes every vertex, where the sum
of the weights of the edges is minimized.
Prim's algorithm works by starting from an arbitrary vertex and iteratively growing
the MST by adding the cheapest edge that connects a vertex in the MST to a vertex
outside the MST.
Example :
The minimum spanning tree is formed by edges (0, 1), (0, 3), and (1, 2), with a total
weight of 6 + 1 + 3 = 10.
Algorithm:
1. Initialize an empty set MST to store the minimum spanning tree and a priority
queue pq to store edges.
2. Choose an arbitrary starting vertex start.
3. Add start to MST.
4. For each edge (start, v) connected to start, add v and the edge weight to pq.
5. While MST does not contain all vertices:
• Remove the edge with the minimum weight from pq.
• If the edge connects a vertex v already in MST to a vertex u outside MST, add
u to MST and the edge to the MST.
• If the edge connects two vertices outside MST, discard the edge.
6. Repeat step 5 until MST contains all vertices.
CODE :
#include <stdio.h>
#include <limits.h>
#define vertices 5
int main() {
int g[vertices][vertices] = {
{0, 0, 3, 0, 0},
{0, 0, 10, 4, 0},
{3, 10, 0, 2, 6},
{0, 4, 2, 0, 1},
{0, 0, 6, 1, 0},
};
int parent[vertices];
int k[vertices];
int mst[vertices];
int i, count, edge, v;
k[0] = 0;
parent[0] = -1;
edge = min;
mst[edge] = 1;
return 0;
}
OUTPUT:
TIME COMPLEXITY:
The time complexity of Prim's algorithm implemented with a priority queue is O(E log
V), where E is the number of edges and V is the number of vertices. This is because, in
each iteration, we extract the minimum edge from the priority queue, which takes
O(log V) time, and we iterate through all edges and vertices.