0% found this document useful (0 votes)
13 views1 page

prims

This document contains a C program that implements Prim's algorithm to find the Minimum Spanning Tree (MST) of a graph. It defines functions to find the minimum key and to construct the MST using an adjacency matrix input by the user. The program prompts for the number of vertices and the adjacency matrix, then outputs the edges and their weights in the MST.

Uploaded by

swetha.v
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)
13 views1 page

prims

This document contains a C program that implements Prim's algorithm to find the Minimum Spanning Tree (MST) of a graph. It defines functions to find the minimum key and to construct the MST using an adjacency matrix input by the user. The program prompts for the number of vertices and the adjacency matrix, then outputs the edges and their weights in the MST.

Uploaded by

swetha.v
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/ 1

//prims

#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#define MAX 100
int findMinKey(int key[], bool inMST[], int vertices) {
int min = INT_MAX, minIndex;
for (int v = 0; v < vertices; v++) {
if (!inMST[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
void primMST(int graph[MAX][MAX], int vertices) {
int parent[MAX];
int key[MAX];
bool inMST[MAX];
for (int i = 0; i < vertices; i++) {
key[i] = INT_MAX;
inMST[i] = false;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < vertices - 1; count++) {
int u = findMinKey(key, inMST, vertices);
inMST[u] = true;
for (int v = 0; v < vertices; v++) {
if (graph[u][v] && !inMST[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
printf("Edge \tWeight\n");
for (int i = 1; i < vertices; i++) {
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
}
int main() {
int vertices, i, j;
printf("Enter the number of vertices: ");
scanf("%d", &vertices);
int graph[MAX][MAX];
printf("Enter the adjacency matrix (enter 0 if no edge exists):\n");
for (i = 0; i < vertices; i++) {
for (j = 0; j < vertices; j++) {
scanf("%d", &graph[i][j]);
}
}
primMST(graph, vertices);
return 0;
}

You might also like