daa6
daa6
Problem Statement:
Write a program in C to perform Prims Algorithm.
Algorithm:
1. Input the number of vertices V from the user.
2. Input the adjacency matrix representing the graph (as a 1D array for flattened 2D
indexing).
3. Initialize arrays:
o key[]: Holds the minimum weight edge that connects a vertex to the MST.
Initialize all to INF, except key[0] = 0.
o mstSet[]: Tracks whether a vertex is included in the MST (1) or not (0).
o parent[]: Stores the parent of each vertex in the MST.
o totalCost = 0: To store the total weight of the MST.
4. Repeat V-1 times (since MST has V-1 edges):
o Find the vertex u not in mstSet[] with the minimum key value.
o Mark u as included in MST: mstSet[u] = 1.
o For every adjacent vertex v of u:
▪ If there is an edge from u to v (i.e., graph[u][v] is non-zero),
▪ and v is not yet in the MST,
▪ and the weight of the edge is less than key[v],
▪ Then update key[v] = graph[u][v] and parent[v] = u.
5. After constructing the MST:
o For each vertex from 1 to V-1:
▪ Print the edge parent[i] - i and its weight.
▪ Add its weight to totalCost.
6. Print the total cost of the MST.
Code:
#include <stdio.h>
#define INF 999999
int minKey(int key[], int mstSet[], int V) {
int min = INF, minIndex = -1;
for (int v = 0; v < V; v++) {
if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
void primMST(int graph[], int V) {
int parent[V];
int key[V];
int mstSet[V];
int totalCost = 0;
for (int i = 0; i < V; i++) {
key[i] = INF;
mstSet[i] = 0;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet, V);
mstSet[u] = 1;
for (int v = 0; v < V; v++) {
if (graph[u * V + v] && mstSet[v] == 0 && graph[u * V + v] < key[v]) {
key[v] = graph[u * V + v]
parent[v] = u;
}
}
}
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d\n", parent[i], i, graph[i * V + parent[i]]);
totalCost += graph[i * V + parent[i]];
}
printf("Total cost of MST: %d\n", totalCost);
}
int main() {
int V;
printf("Enter the number of vertices: ");
scanf("%d", &V);
int graph[V * V];
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
scanf("%d", &graph[i * V + j]);
}
}
primMST(graph, V);
return 0;
}
Output:
Complexity Analysis:
• Time Complexity: O (𝑉 2 )
• Space Complexity: O (𝑉 2 )