Explain Prim's algorithm for minimum spanning tree with example. न्यूनतम अवशेष वृक्ष के लिए प्रिम एल्गोरिथ्म को उदाहरण सहित समझाइए |
Q.) Explain Prim's algorithm for minimum spanning tree with example. न्यूनतम अवशेष वृक्ष के लिए प्रिम एल्गोरिथ्म को उदाहरण सहित समझाइए |
Subject: Data StructuresPrim's algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. The algorithm operates by building this tree one vertex at a time, from an arbitrary starting vertex, at each step adding the cheapest possible connection from the tree to another vertex.
Here is a step-by-step approach to Prim's algorithm:
Initialize: Start with a tree
T
containing a single vertex (arbitrarily chosen).Grow the Tree: At each step, add the cheapest edge that connects a vertex in the tree to a vertex outside the tree.
Repeat: Continue this process until all vertices are included in
T
.Result: The tree
T
is now a minimum spanning tree of the graph.
Let's illustrate Prim's algorithm with an example. Consider the following graph:
A --1-- B
| / \
| / \
4 2 3
| / \
| / \
C --3-- D --1-- E
Here's how Prim's algorithm would work on this graph:
Initialize: Start with a vertex, say
A
. SoT = {A}
.Step 1: Look for the cheapest edge connecting
T
to a vertex not inT
. The cheapest edge isA-B
with a weight of 1. AddB
toT
.Step 2: Now,
T = {A, B}
. The cheapest edges connectingT
to vertices not inT
areB-C
andB-E
, both with a weight of 2. We can choose either, so let's say we chooseB-C
. AddC
toT
.Step 3: Now,
T = {A, B, C}
. The cheapest edge isC-D
with a weight of 3. AddD
toT
.Step 4: Now,
T = {A, B, C, D}
. The only vertex not inT
isE
. The cheapest edge connectingE
toT
isD-E
with a weight of 1. AddE
toT
.Result: All vertices are now in
T
, and we have our minimum spanning tree:
A --1-- B
|
|
2
|
C --3-- D --1-- E
The total weight of the minimum spanning tree is 1 + 2 + 3 + 1 = 7
.
Here is a table summarizing the steps:
Step | Tree T |
Cheapest Edge Added | New Vertex Added | Total Weight |
---|---|---|---|---|
0 | {A} | - | - | 0 |
1 | {A, B} | A-B (1) | B | 1 |
2 | {A, B, C} | B-C (2) | C | 3 |
3 | {A, B, C, D} | C-D (3) | D | 6 |
4 | {A, B, C, D, E} | D-E (1) | E | 7 |
The algorithm ensures that the tree remains acyclic and connected at each step, and the greedy choice of adding the cheapest edge guarantees that the final tree is of minimum total weight.