- Asked 2/14
- 2070 Magh · 5 marks
- 2068 Bhadra · 4 marks
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.
| Step | Tree T | Candidate edges leaving T | Chosen |
|---|---|---|---|
| 1 | {A} | A-B 2, A-C 6, A-F 7 | A-B (2) |
| 2 | {A,B} | A-C 6, A-F 7, B-D 11 | A-C (6) |
| 3 | {A,B,C} | C-F 3, C-E 5, A-F 7, B-D 11 | C-F (3) |
| 4 | {A,B,C,F} | F-E 1, C-E 5, F-D 9, B-D 11 | F-E (1) |
| 5 | {A,B,C,E,F} | F-D 9, B-D 11 | F-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)
Related questions
- Spanning tree properties; Round Robin MST · Data Structure and Algorithm, chapter 10
- TOH algorithm and recursion tree · Data Structure and Algorithm, chapter 5 · asked 2×
- B-tree insertion algorithm; AVL of months · Data Structure and Algorithm, chapter 6 · asked 2×
- Kruskal's algorithm with example · Data Structure and Algorithm, chapter 10 · asked 3×
- Write Kruskal's algorithm · Data Structure and Algorithm, chapter 10 · asked 3×
- Kruskal's MST on graph A to G · Data Structure and Algorithm, chapter 10 · asked 3×
- Short note: Spanning tree and applications · Discrete Structure, chapter 4
- Short note: Spanning tree · Discrete Structure, chapter 4 · asked 3×
- Decision tree classifier and Hunt's algorithm · Data Mining, chapter 3
- Huffman code tree steps with example · Multimedia System, chapter 5 · asked 7×