0% found this document useful (0 votes)
9 views4 pages

Program No 9 (A)

Uploaded by

Akul Kumar
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)
9 views4 pages

Program No 9 (A)

Uploaded by

Akul Kumar
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/ 4

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+Elog⁡V)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.

5. Stop when all vertices are included in the MST.

Process:
1. Input the number of vertices and the graph as an adjacency matrix.

2. Use an array to keep track of the parent of each vertex.

3. Use another array to store the minimum key values.

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>

#define V 5 // Number of vertices in the graph

int findMinKey(int key[], bool mstSet[]) {

int min = INT_MAX, minIndex;


for (int v = 0; v < V; v++) {

if (!mstSet[v] && key[v] < min) {

min = key[v];

minIndex = v;

return minIndex;

void primMST(int graph[V][V]) {

int parent[V];

int key[V];

bool mstSet[V];

for (int i = 0; i < V; i++) {

key[i] = INT_MAX;

mstSet[i] = false;

key[0] = 0;

parent[0] = -1;

for (int count = 0; count < V - 1; count++) {

int u = findMinKey(key, mstSet);

for (int v = 0; v < V; v++) {

if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {

parent[v] = u;

key[v] = graph[u][v];

}
printf("Edge \tWeight\n");

for (int i = 1; i < V; i++) {

printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);

int main() {

int graph[V][V];

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

for (int i = 0; i < V; i++) {

for (int j = 0; j < V; j++) {

scanf("%d", &graph[i][j]);

printf("\nRunning Prim's Algorithm to find MST...\n");

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

You might also like