Program No 9 (A)
Program No 9 (A)
Aim: Write a program to implement Prim's Algorithm to find the Minimum Spanning Tree
(MST).
Complexity:
Worst-case complexity: O(V2)O(V^2)O(V2) for dense graphs using adjacency matrix.
Best-case complexity: O(V+ElogV)O(V + E \log V)O(V+ElogV) for sparse graphs using
adjacency list and priority queues.
Algorithm:
1. Start with an empty MST.
2. Assign an initial key value of 0 to the first vertex and infinite key values to all others.
3. Repeatedly select the vertex with the smallest key value that is not yet included in the MST.
4. Update the key values of the adjacent vertices if a smaller edge weight is found.
Process:
1. Input the number of vertices and the graph as an adjacency matrix.
4. Traverse the graph and print the edges of the MST along with their weights.
Source Code:
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
min = key[v];
minIndex = v;
return minIndex;
int parent[V];
int key[V];
bool mstSet[V];
key[i] = INT_MAX;
mstSet[i] = false;
key[0] = 0;
parent[0] = -1;
parent[v] = u;
key[v] = graph[u][v];
}
printf("Edge \tWeight\n");
int main() {
int graph[V][V];
scanf("%d", &graph[i][j]);
primMST(graph);
return 0;
}
Sample Input and Output
Input:
Enter the adjacency matrix of the graph (use 0 for no connection):
02060
20385
03007
68009
05790
Output:
Running Prim's Algorithm to find MST...
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5