DATA STRUCTURES PROGRAM • GRAPHS
Find a Minimum Spanning Tree with Prim's Algorithm
Learn how to find a minimum spanning tree with prim's algorithm using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0-1(2) 1-2(3) 0-3(6) 1-4(5) Cost = 16
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <limits.h>
int main(void)
{
int graph[5][5] = {
{0,2,0,6,0}, {2,0,3,8,5}, {0,3,0,0,7}, {6,8,0,0,9}, {0,5,7,9,0}
};
int key[5] = {0, INT_MAX, INT_MAX, INT_MAX, INT_MAX};
int parent[5] = {-1,-1,-1,-1,-1}, used[5] = {0};
for (int step = 0; step < 5; step++) {
int vertex = -1;
for (int candidate = 0; candidate < 5; candidate++)
if (!used[candidate] && (vertex < 0 || key[candidate] < key[vertex])) vertex = candidate;
used[vertex] = 1;
for (int neighbour = 0; neighbour < 5; neighbour++)
if (graph[vertex][neighbour] && !used[neighbour] && graph[vertex][neighbour] < key[neighbour]) {
key[neighbour] = graph[vertex][neighbour]; parent[neighbour] = vertex;
}
}
int cost = 0;
for (int vertex = 1; vertex < 5; vertex++) {
printf("%d-%d(%d) ", parent[vertex], vertex, graph[parent[vertex]][vertex]);
cost += graph[parent[vertex]][vertex];
}
printf("\nCost = %d\n", cost);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0-1(2) 1-2(3) 0-3(6) 1-4(5) Cost = 16
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Repeatedly attach the unused vertex with the cheapest edge into the growing tree.
- Display the computed result.
Repeatedly attach the unused vertex with the cheapest edge into the growing tree.
EFFICIENCY
Time and space complexity
Time complexity
O(V²)
Auxiliary space
O(V)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
