0
0
DSA Cprogramming

Minimum Spanning Tree Prim's Algorithm in DSA C

Choose your learning style9 modes available
Mental Model
Prim's algorithm grows a tree by adding the cheapest edge that connects a new node to the tree until all nodes are included.
Analogy: Imagine building a road network connecting cities. You start from one city and always pick the shortest road to a city not yet connected, gradually linking all cities with minimum total road length.
Graph nodes: 1, 2, 3, 4
Edges with weights:
1 --2-- 2
1 --3-- 3
2 --1-- 3
2 --4-- 4
3 --5-- 4

Initial tree:
[1] (start node)
Other nodes: 2, 3, 4
Dry Run Walkthrough
Input: Graph with nodes 1, 2, 3, 4 and edges: (1-2:2), (1-3:3), (2-3:1), (2-4:4), (3-4:5). Start from node 1.
Goal: Build a minimum spanning tree connecting all nodes with minimum total edge weight.
Step 1: Start from node 1, add it to MST set.
MST nodes: [1]
Edges considered: (1-2:2), (1-3:3)
Why: We begin from node 1 and look at edges from it to find the cheapest connection.
Step 2: Pick edge (1-2) with weight 2, add node 2 to MST.
MST nodes: 1 -> [2]
Edges considered: (2-3:1), (2-4:4), (1-3:3)
Why: Edge (1-2) is the cheapest from MST to outside nodes, so add node 2.
Step 3: Pick edge (2-3) with weight 1, add node 3 to MST.
MST nodes: 1 -> 2 -> [3]
Edges considered: (3-4:5), (2-4:4), (1-3:3 but 3 already in MST)
Why: Edge (2-3) is now the cheapest edge connecting MST to outside nodes.
Step 4: Pick edge (2-4) with weight 4, add node 4 to MST.
MST nodes: 1 -> 2 -> 3 -> [4]
All nodes included, MST complete.
Why: Edge (2-4) is the cheapest edge connecting MST to the last outside node.
Result:
Minimum Spanning Tree edges:
1 --2-- 2
2 --1-- 3
2 --4-- 4
Total weight = 7
Annotated Code
DSA C
#include <stdio.h>
#include <limits.h>

#define V 4

int minKey(int key[], int mstSet[]) {
    int min = INT_MAX, min_index = -1;
    for (int v = 0; v < V; v++) {
        if (mstSet[v] == 0 && key[v] < min) {
            min = key[v];
            min_index = v;
        }
    }
    return min_index;
}

void primMST(int graph[V][V]) {
    int parent[V];
    int key[V];
    int mstSet[V];

    for (int i = 0; i < V; i++) {
        key[i] = INT_MAX;
        mstSet[i] = 0;
    }

    key[0] = 0;
    parent[0] = -1;

    for (int count = 0; count < V - 1; count++) {
        int u = minKey(key, mstSet);
        if (u == -1) {
            break; // No more reachable vertices
        }
        mstSet[u] = 1;

        for (int v = 0; v < V; v++) {
            if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
                parent[v] = u;
                key[v] = graph[u][v];
            }
        }
    }

    printf("Edge \tWeight\n");
    int total_weight = 0;
    for (int i = 1; i < V; i++) {
        if (parent[i] != -1) {
            printf("%d - %d \t%d\n", parent[i] + 1, i + 1, graph[i][parent[i]]);
            total_weight += graph[i][parent[i]];
        }
    }
    printf("Total weight = %d\n", total_weight);
}

int main() {
    int graph[V][V] = {
        {0, 2, 3, 0},
        {2, 0, 1, 4},
        {3, 1, 0, 5},
        {0, 4, 5, 0}
    };

    primMST(graph);
    return 0;
}
int u = minKey(key, mstSet);
Select the next node with the smallest key value not yet in MST
mstSet[u] = 1;
Add selected node to MST set
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
Update key and parent if edge offers cheaper connection to MST
parent[v] = u;
Record the MST connection for node v
key[v] = graph[u][v];
Update minimum edge weight to node v
OutputSuccess
Edge Weight 1 - 2 2 2 - 3 1 2 - 4 4 Total weight = 7
Complexity Analysis
Time: O(V^2) because we scan all vertices to find the minimum key in each iteration and update keys for all adjacent vertices.
Space: O(V) for arrays storing keys, parents, and MST set membership.
vs Alternative: Compared to Kruskal's algorithm which sorts edges O(E log E), Prim's is better for dense graphs with adjacency matrix representation.
Edge Cases
Graph with single node
Algorithm returns immediately with no edges in MST.
DSA C
for (int count = 0; count < V - 1; count++) {
Disconnected graph
Algorithm only builds MST for connected component containing start node; other nodes remain unreachable.
DSA C
int u = minKey(key, mstSet); // returns -1 if no reachable node
Graph with equal edge weights
Algorithm picks edges in order of node indices when weights tie, still producing a valid MST.
DSA C
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
When to Use This Pattern
When you need to connect all points with minimum total cost and the graph is dense or given as adjacency matrix, reach for Prim's algorithm because it grows the MST by adding the cheapest edge from the tree to a new node.
Common Mistakes
Mistake: Not updating the key array when a cheaper edge is found.
Fix: Always update key[v] when a smaller edge weight is found connecting v to MST.
Mistake: Including nodes multiple times by not marking them in mstSet.
Fix: Mark nodes as included in MST immediately after selecting them.
Summary
Prim's algorithm builds a minimum spanning tree by adding the cheapest edge connecting a new node to the growing tree.
Use it when you want to connect all nodes with minimum total edge weight, especially in dense graphs.
The key insight is to keep track of the cheapest edge to each node outside the MST and pick the smallest one each step.