Skip to main content

Prim's algorithm with example

Short answer

Prim grows a tree by adding the cheapest edge connecting a tree vertex to an outside vertex. Starting at A, the chosen edges are A-B(2), A-C(6), C-F(3), F-E(1), F-D(9); MST cost is 21.

Explain Prim's algorithm for finding minimum spanning tree along with an example.

A minimum spanning tree (MST) of a connected weighted undirected graph is a spanning tree with the smallest total edge weight.

Prim's algorithm is a greedy method that grows a single tree from a start vertex. At each step it adds the cheapest edge that connects a vertex in the tree to a vertex outside the tree.

Algorithm

PRIM(G, start)
1. T = {start};  MST edges = empty
2. while T does not contain all vertices
3.     pick the minimum-weight edge (u, v) with u in T and v not in T
4.     add v to T and edge (u, v) to the MST
/* cost[i][j] = weight, INF if no edge */
int prim(int n, int cost[][N]) {
    int total = 0, in[N] = {0};
    in[0] = 1;
    for (int i = 0; i < n - 1; i++) {
        int min = INF, u = -1, v = -1;
        for (int a = 0; a < n; a++) if (in[a])
            for (int b = 0; b < n; b++)
                if (!in[b] && cost[a][b] < min) { min = cost[a][b]; u = a; v = b; }
        in[v] = 1; total += min;
        printf("%d-%d (%d)\n", u, v, min);
    }
    return total;
}

Complexity: O(V²) with a matrix (using a key array), O(E log V) with a heap.

Example

Graph: A-B 2, A-C 6, A-F 7, B-D 11, C-F 3, C-E 5, D-F 9, E-F 1. Start at A.

StepTree TCandidate edges leaving TChosen
1{A}A-B 2, A-C 6, A-F 7A-B (2)
2{A,B}A-C 6, A-F 7, B-D 11A-C (6)
3{A,B,C}C-F 3, C-E 5, A-F 7, B-D 11C-F (3)
4{A,B,C,F}F-E 1, C-E 5, F-D 9, B-D 11F-E (1)
5{A,B,C,E,F}F-D 9, B-D 11F-D (9)

MST edges: A-B, A-C, C-F, F-E, F-D. Minimum cost = 2 + 6 + 3 + 1 + 9 = 21.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 10 questions →