0% found this document useful (0 votes)
5 views2 pages

Partb 7

Uploaded by

gagan k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Partb 7

Uploaded by

gagan k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <limits.h>

#define MAX 100

// Function to find the vertex with the minimum key value that is not yet included
in the MST
int minKey(int key[], int mstSet[], int n) {
int min = INT_MAX, minIndex;
int v;
for ( v = 0; v < n; v++) {
if (mstSet[v] == 0 && key[v] < min) {
min = key[v], minIndex = v;
}
}
return minIndex;
}

// Function to print the constructed MST


void printMST(int parent[], int graph[MAX][MAX], int n) {
int i;
printf("Edge \tWeight\n");
for ( i = 1; i < n; i++) {
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
}

// Function to construct and print the MST using Prim's algorithm


void primMST(int graph[MAX][MAX], int n) {
int parent[MAX]; // Array to store constructed MST
int key[MAX]; // Key values to pick the minimum weight edge
int mstSet[MAX]; // To represent the set of vertices included in MST
int i,v,count;
// Initialize all keys to infinity and mstSet[] to false
for ( i = 0; i < n; i++) {
key[i] = INT_MAX;
mstSet[i] = 0;
}

// Always include the first vertex in MST


key[0] = 0; // Make key 0 so that this vertex is picked first
parent[0] = -1; // First node is always the root of MST

// The MST will have n vertices


for ( count = 0; count < n - 1; count++) {
// Pick the minimum key vertex not yet included in MST
int u = minKey(key, mstSet, n);

// Add the picked vertex to the MST set


mstSet[u] = 1;

// Update the key and parent for adjacent vertices of u


for ( v = 0; v < n; v++) {
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
// Print the constructed MST
printMST(parent, graph, n);
}

int main() {
int n,i,j;
int graph[MAX][MAX];

printf("Enter the number of vertices: ");


scanf("%d", &n);

printf("Enter the adjacency matrix (use 0 for no edge):\n");


for ( i = 0; i < n; i++) {
for ( j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}

// Apply Prim's algorithm


primMST(graph, n);

return 0;
}

You might also like