0% found this document useful (0 votes)
3 views

Kruskal and prim's algorithm

The document outlines Kruskal's and Prim's algorithms for finding the Minimum Spanning Tree (MST) in a weighted undirected graph. Kruskal's algorithm involves sorting edges by weight and adding them to the MST while avoiding cycles, while Prim's algorithm starts from an arbitrary vertex and continuously adds the minimum-cost edge connecting visited and unvisited vertices. Both algorithms are demonstrated with examples, including adjacency matrices and step-by-step selections of edges.

Uploaded by

b8618044414
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Kruskal and prim's algorithm

The document outlines Kruskal's and Prim's algorithms for finding the Minimum Spanning Tree (MST) in a weighted undirected graph. Kruskal's algorithm involves sorting edges by weight and adding them to the MST while avoiding cycles, while Prim's algorithm starts from an arbitrary vertex and continuously adds the minimum-cost edge connecting visited and unvisited vertices. Both algorithms are demonstrated with examples, including adjacency matrices and step-by-step selections of edges.

Uploaded by

b8618044414
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Kruskal's Algorithm for Minimum Spanning Tree (MST)

Algorithm:
1. Sort all edges in the graph in ascending order of their weights.
2. Initialize an empty spanning tree (T) and set the cost to 0.
3. For each edge in sorted order:
o Find the root of both vertices of the edge using the Find() function.
o If they belong to different sets (i.e., adding the edge does not form a cycle):
▪ Include this edge in the MST.
▪ Merge the sets using the Union() function.
▪ Add the edge weight to the total cost.
4. Repeat until (n - 1) edges are added to the spanning tree (where n is the number of
vertices).
5. Output the MST and its total cost.
KRUSKAL(G): 1. Sort all edges in increasing order of weight. 2. Initialize an empty set MST = {} and
minCost = 0. 3. For each edge (u, v) in sorted order: a. If FIND(u) ≠ FIND(v): // If u and v belong to
different sets i. Add (u, v) to MST. ii. UNION(u, v). iii. minCost += weight of (u, v). 4. If the number of
edges in MST = (n - 1), stop. 5. Return MST and minCost.
Functions Used:
1. Find(u): Determines the root of the set containing u (using path compression for efficiency).
2. Union(u, v): Merges two sets (by rank or size to keep the tree balanced).
Time Complexity Analysis
• Sorting edges: O(Elog⁡E)O(E \log E)O(ElogE)
• Find & Union operations (with path compression): O(α(E))O(\alpha(E))O(α(E)), where
α\alphaα is the inverse Ackermann function (almost constant time).
• Overall complexity: O(Elog⁡E)O(E \log E)O(ElogE), where E is the number of edges.
• #include <stdio.h>

• int i, j, u, v, n, ne = 1;
• int min, mincost = 0, cost[10][10], parent[10];

• int find(int i);
• int uni(int i, int j);

• int main() {
• printf("\n\tImplementation of Kruskal's Algorithm\n");

• // Input the number of vertices
• printf("\nEnter the number of vertices: ");
• scanf("%d", &n);

• // Input the cost adjacency matrix
• printf("\nEnter the cost adjacency matrix:\n");
• for (i = 1; i <= n; i++) {
• for (j = 1; j <= n; j++) {
• scanf("%d", &cost[i][j]);
• if (cost[i][j] == 0)
• cost[i][j] = 999; // Set zero edges to "infinity"
(except diagonal)
• }
• parent[i] = 0; // Initialize parent array
• }

• printf("\nThe edges of the Minimum Cost Spanning Tree are:\n");

• while (ne < n) { // Runs until we include (n-1) edges
• min = 999; // Reset min before each iteration

• // Find the minimum cost edge
• for (i = 1; i <= n; i++) {
• for (j = 1; j <= n; j++) {
• if (cost[i][j] < min) {
• min = cost[i][j];
• u = i;
• v = j;
• }
• }
• }

• int rootU = find(u);
• int rootV = find(v);

• if (uni(rootU, rootV)) { // If it does not form a cycle,
include it
• printf("%d edge (%d, %d) = %d\n", ne++, u, v, min);
• mincost += min;
• }

• // Remove the edge from consideration
• cost[u][v] = cost[v][u] = 999;
• }

• printf("\nMinimum Cost = %d\n", mincost);
• return 0;
• }

• // Find function with path compression
• int find(int i) {
• while (parent[i] != 0)
• i = parent[i];
• return i;
• }

• // Union function to join sets
• int uni(int i, int j) {
• if (i != j) {
• parent[j] = i; // Union operation
• return 1;
• }
• return 0;
• }

Undirected Graph with 4 Vertices


Consider an undirected, weighted graph with 4 vertices (A, B, C, D) and 5 edges:
css
CopyEdit
(A)
/ \
1/ \4
/ \
(B)------(C)
2 \5
(D)
Graph Representation (Adjacency Matrix)
A B C D
A 0 1 4 999
B 1 0 2 5
C 4 2 0 3
D 999 5 3 0
Here, 999 represents no direct edge between two vertices.

Applying Kruskal's Algorithm to Find MST


Step 1: Sort All Edges in Ascending Order
Edge Weight
(A, B) 1
(B, C) 2
(C, D) 3
(A, C) 4
(B, D) 5
Step 2: Select Edges to Form MST
• Start with an empty set MST = {}.
• Add edges without forming cycles.
Step Edge Selected MST Edges Min Cost

1 (A, B) - 1 {(A, B)} 1

2 (B, C) - 2 {(A, B), (B, C)} 3

3 (C, D) - 3 {(A, B), (B, C), (C, D)} 6

4 (A, C) - 4 Ignored (Cycle) 6

5 (B, D) - 5 Ignored (Cycle) 6


Result:
The Minimum Spanning Tree (MST) contains:
css
CopyEdit
(A, B) - 1
(B, C) - 2
(C, D) - 3
with Minimum Cost = 6.
Program:2 Prim’s algorithm
#include <stdio.h>

#define INF 9999


int cost[10][10], n, mincost = 0;

int prims();

int main() {
printf("********* PRIM'S ALGORITHM *********\n");
printf("Enter the number of nodes: ");
scanf("%d", &n);

printf("Enter the cost matrix:\n");


for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf("%d", &cost[i][j]);
if (cost[i][j] == 0)
cost[i][j] = INF; // Replace 0 with "infinity" except diagonal
}
}

printf("\nMinimum Spanning Tree Edges and Costs:\n");


mincost = prims();
printf("\nThe Minimum Spanning Tree Cost is: %d\n", mincost);

return 0;
}

int prims() {
int nearV[10];
int t[10][3]; // Stores the MST edges
int u = 1, v = 1;
int min, i, j, k;

// Initialize nearV[]
for (i = 1; i <= n; i++)
nearV[i] = 0;

nearV[1] = 1; // Start from vertex 1

for (i = 1; i < n; i++) {


min = INF;

// Find the minimum cost edge


for (j = 1; j <= n; j++) {
if (nearV[j]) { // If the vertex is already included
for (k = 1; k <= n; k++) {
if (!nearV[k] && cost[j][k] < min) { // If it's a new vertex
min = cost[j][k];
u = j;
v = k;
}
}
}
}
// Store the edge in MST
t[i][1] = u;
t[i][2] = v;
mincost += min;
nearV[v] = 1; // Mark the new vertex as included

printf("Edge: %d -> %d, Cost = %d\n", u, v, min);


}

return mincost;
}

Prim’s Algorithm for Minimum Spanning Tree (MST)


Prim's algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) for a given
undirected, weighted graph.

Algorithm:
1. Initialize:
o Choose an arbitrary vertex as the starting point.
o Mark it as visited and initialize an array to track the nearest vertices.
2. Iterate until all vertices are included in MST:
o Select the minimum-cost edge that connects a visited vertex to an unvisited vertex.
o Add the selected edge to the MST.
o Update the nearest vertices for the remaining unvisited vertices.
3. Stop when the MST contains (n - 1) edges.
4. Output the MST and its total cost.

Pseudocode for Prim’s Algorithm


plaintext
CopyEdit
PRIM(G, n):
1. Select an arbitrary vertex as the starting vertex.
2. Initialize an array `nearV[]` to track the nearest vertices.
3. Mark the starting vertex as included in MST.
4. Repeat (n-1) times:
a. Find the minimum-cost edge connecting a visited vertex to an unvisited vertex.
b. Add the selected edge to MST.
c. Update `nearV[]` for the remaining unvisited vertices.
5. Output the MST edges and total cost.

Example: Find MST for an Undirected Graph with 4 Vertices


Given Graph:
mathematica
CopyEdit
(A)
/ \
1/ \4
/ \
(B)-----(C)
| /
2| /3
| /
(D)
Graph Representation (Adjacency Matrix):
A B C D
A B C D
A 0 1 4 3
B 1 0 2 999
C 4 2 0 3
D 3 999 3 0
(999 represents no direct edge between two vertices)

Applying Prim’s Algorithm


Step 1: Initialize
• Start from vertex A.
• nearV[] keeps track of the nearest vertex for each unvisited node.
Step 2: Select Minimum Edges
Step Edge Selected MST Edges Min Cost

1 (A, B) - 1 {(A, B)} 1

2 (B, C) - 2 {(A, B), (B, C)} 3

3 (C, D) - 3 {(A, B), (B, C), (C, D)} 6


Final MST and Cost
mathematica
CopyEdit
(A)----(B)
|
(C)
|
(D)
Total Minimum Cost = 6.

Final Answer:
The Minimum Spanning Tree (MST) found using Prim’s Algorithm consists of edges:
1. (A, B) with weight 1
2. (B, C) with weight 2
3. (C, D) with weight 3
with a Total Cost = 6.

You might also like