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.

AdvancedPrimMinimum spanning treeGreedy

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

dsa-prim-minimum-spanning-tree.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

0-1(2) 1-2(3) 0-3(6) 1-4(5)
Cost = 16
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Repeatedly attach the unused vertex with the cheapest edge into the growing tree.
  3. 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.