Prims
Prims
Prims
h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#define MAX_VERTICES 150
#define INF INT_MAX
typedef struct {
int vertex;
int weight;
} Edge;
typedef struct Node {
Edge edge;
struct Node* left;
struct Node* right;
} Node;
Node* createNode(Edge edge);
void insert(Node** root, Edge edge);
Edge extractMin(Node** root);
int isEmpty(Node* root);
void prim(int graph[MAX_VERTICES][MAX_VERTICES], int numVertices, int startVertex);
void
generateGraph(int graph[MAX_VERTICES][MAX_VERTICES], int numVertices, int
numEdges); void
freeHeap(Node* node);
int main() {
int numVertices, numEdges;
printf("Enter the number of vertices: ");
scanf("%d", &numVertices);
printf("Enter the number of edges: ");
scanf("%d", &numEdges);
}
Edge extractMin(Node** root) {
if (isEmpty(*root)) {
Edge nullEdge = {-1, -1};
return nullEdge;
}
Node* minNode = *root;
Edge minEdge = minNode->edge;
if (minNode->left) {
*root = minNode->left;
Node* rightChild = minNode->right;
Node* temp = *root;
while (temp->right) {
temp = temp->right;
}
temp->right = rightChild;
} else {
*root = minNode->right;
}
free(minNode);
return minEdge;
}
int isEmpty(Node* root) {
return root == NULL;
}
void prim(int graph[MAX_VERTICES][MAX_VERTICES], int numVertices, int startVertex)
{
int inMST[MAX_VERTICES] = {0};
Node* root = NULL;
Edge currentEdge;
int totalWeight = 0;
inMST[startVertex] = 1;
for (int i = 0; i < numVertices; i++) {
if (graph[startVertex][i] > 0) {
Edge edge = {i, graph[startVertex][i]};
insert(&root, edge);
}
}
printf("Edges in the Minimum Spanning Tree:\n");
while (!isEmpty(root)) {
currentEdge = extractMin(&root);
int nextVertex = currentEdge.vertex;
if (inMST[nextVertex]) {
continue;
}
printf("%d - %d (weight: %d)\n", startVertex, nextVertex,
currentEdge.weight); totalWeight += currentEdge.weight;
inMST[nextVertex] = 1;
startVertex = nextVertex;
for (int i = 0; i < numVertices; i++) {
if (graph[nextVertex][i] > 0 && !inMST[i]) {
Edge edge = {i, graph[nextVertex][i]};
insert(&root, edge);
}
}
}
printf("Total weight of MST: %d\n", totalWeight);
freeHeap(root);
}
void generateGraph(int graph[MAX_VERTICES][MAX_VERTICES], int numVertices, int
numEdges) {
srand(time(NULL));
for (int i = 0; i < numEdges; i++) {
int u = rand() % numVertices;
int v = rand() % numVertices;
int weight = rand() % 10 + 1;
if (u != v && graph[u][v] == 0) {
graph[u][v] = weight;
graph[v][u] = weight;
}
}
}
void freeHeap(Node* node) {
if (node) {
freeHeap(node->left);
freeHeap(node->right);
free(node);
}
}