Minimum Spanning Tree
Minimum Spanning Tree
Minimum Spanning Tree
• Kruskal’s Algorithm:
Input:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
struct Edge
};
struct Graph
int V, E;
};
graph->V = V;
graph->E = E;
return graph;
struct subset
int parent;
int rank;
};
if (subsets[i].parent != i)
return subsets[i].parent;
subsets[xroot].parent = yroot;
subsets[yroot].parent = xroot;
else
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
int V = graph->V;
int e = 0;
int i = 0;
subsets[v].parent = v;
subsets[v].rank = 0;
while (e < V - 1)
if (x != y)
result[e++] = next_edge;
Union(subsets, x, y);
result[i].weight);
return;
int main()
int V = 4;
int E = 5;
struct Graph* graph = createGraph(V, E);
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = 10;
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 6;
graph->edge[2].src = 0;
graph->edge[2].dest = 3;
graph->edge[2].weight = 5;
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 15;
graph->edge[4].src = 2;
graph->edge[4].dest = 3;
graph->edge[4].weight = 4;
KruskalMST(graph);
return 0;
}
output:
• Prim’s Algorithm:
Input:
#include <iostream>
#include <cstring>
#define V 5
int G[V][V] = {
{0, 3, 0, 3, 0},
{3, 0, 0, 0, 4},
{0, 0, 0, 2, 1},
{3, 3, 2, 0, 0},
{0, 4, 1, 0, 0}};
int main () {
int num_edge;
int mst_vertex[V];
num_edge = 0;
mst_vertex[0] = true;
int x;
int y;
x = 0;
y = 0;
if (mst_vertex[i]) {
min = G[i][j];
x = i;
y = j;
cout << x << " - " << y << " : " << G[x][y];
mst_vertex[y] = true;
num_edge++;
return 0;
}
output: