DSA Tutorial



PRIM'S ALGORITHM


🌟 Prim's Algorithm in DSA (Using C)

Prim’s Algorithm helps in finding the Minimum Spanning Tree (MST) from a weighted undirected graph by starting from one node and growing the MST one edge at a time.

🏗️ How It Works:

  • Start from any vertex.
  • Pick the smallest edge connecting the MST to a new vertex.
  • Repeat until all vertices are included.
💡 Use Case: Useful when we want to build a network (roads, cables, pipes) with minimum cost from a starting point.

🧪 C Program for Prim’s Algorithm

#include <stdio.h>
#include <limits.h>

#define V 5

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

void printMST(int parent[], int graph[V][V]) {
    printf("Edge \tWeight\n");
    int totalWeight = 0;
    for (int i = 1; i < V; i++) {
        printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
        totalWeight += graph[i][parent[i]];
    }
    printf("Total Cost of MST: %d\n", totalWeight);
}

void primMST(int graph[V][V]) {
    int parent[V];    // To store MST
    int key[V];       // Used to pick min weight edge
    int mstSet[V];    // Vertices included in MST

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

    key[0] = 0;      // Start from vertex 0
    parent[0] = -1;

    for (int count = 0; count < V - 1; count++) {
        int u = minKey(key, mstSet);
        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];
    }

    printMST(parent, graph);
}

int main() {
    int graph[V][V] = {
        {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}
    };

    primMST(graph);
    return 0;
}
  
Time Complexity: O(V²)
Space Complexity: O(V)

🔍 Output Example

Edge    Weight
0 - 1   2
1 - 2   3
0 - 3   6
1 - 4   5
Total Cost of MST: 16
  
Tip: Prim’s algorithm is efficient for dense graphs. Kruskal’s is better for sparse graphs.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review