0% found this document useful (0 votes)
133 views

Prim's Algorithm Using Adjacency Matrix

This document implements Prim's algorithm to find the minimum spanning tree of a graph. It includes functions to find the minimum key value from the key array, print the minimum spanning tree, and perform Prim's algorithm on a graph represented by an adjacency matrix. Prim's algorithm initializes all keys to infinity and the parent of the first vertex to -1. It then iterates through the vertices, selecting the vertex with minimum key, updating its parent, and relaxing adjacent edges. The minimum spanning tree is then printed.

Uploaded by

Sri Harsha T
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views

Prim's Algorithm Using Adjacency Matrix

This document implements Prim's algorithm to find the minimum spanning tree of a graph. It includes functions to find the minimum key value from the key array, print the minimum spanning tree, and perform Prim's algorithm on a graph represented by an adjacency matrix. Prim's algorithm initializes all keys to infinity and the parent of the first vertex to -1. It then iterates through the vertices, selecting the vertex with minimum key, updating its parent, and relaxing adjacent edges. The minimum spanning tree is then printed.

Uploaded by

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

Implementation of Prims Algorithm

#include <stdio.h>
#include<limits.h>
#include<stdbool.h>
#define V 9
int minKey(int key[ ], bool mstSet[ ])
{
int v;
int min = INT_MAX;
int min_index;
for ( v = 0; v < V; v++)
{
if (mstSet[v] == false && key[v] < min)
{
min = key[v];
min_index = v;
}
}
return min_index;
}

int printMST(int parent[ ], int n, int graph[V][V])


{
int i;
printf("Edge Weight\n");
for ( i = 1; i < V; i++)
printf("%d - %d %d \n", parent[i], i, graph[i][parent[i]]);
}
void primMST(int graph[V][V])
{
int i, v, parent[V];
int key[V];
bool mstSet[V];
for (i = 0; i < V; i++)
{
key[i] = INT_MAX;
mstSet[i] = false;
parent[i]=0;
}
key[0] = 0;
parent[0] = -1;
for (i = 0; i < V-1; i++)
{
int u = minKey(key, mstSet);
mstSet[u] = true;
for ( v = 0; v < V; v++)
if (graph[u][v]!=0 && mstSet[v] == false && graph[u][v] < key[v])
{
parent[v] = u;
key[v] = graph[u][v];
}
}
printMST(parent, V, graph);
}
void main()
{
int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{0, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0},
};
primMST(graph);
}

You might also like