Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

A minimum spanning tree(MST) or minimum weight spanning tree for a weighted, connected, and undirected graph is a spanning tree (no cycles and connects all vertices) that has minimum weight. The weight of a spanning tree is the sum of all edges in the tree.

In Kruskal's algorithm, we sort all edges of the given graph in increasing order. Then it keeps on adding new edges and nodes in the MST if the newly added edge does not form a cycle. It picks the minimum weighted edge at first and the maximum weighted edge at last. Thus we can say that it makes a locally optimal choice in each step in order to find the optimal solution. Hence this is a Greedy Algorithm .

How to find MST using Kruskal's algorithm?

Below are the steps for finding MST using Kruskal's algorithm:

Kruskal's Algorithm uses the Disjoint Set Data Structure to detect cycles.

Illustration:

The graph contains 9 vertices and 14 edges. So, the minimum spanning tree formed will be having (9 - 1) = 8 edges.


C++
#include<bits/stdc++.h>
usingnamespacestd;
// Disjoint set data struture
classDSU{
vector<int>parent,rank;
public:
DSU(intn){
parent.resize(n);
rank.resize(n);
for(inti=0;i<n;i++){
parent[i]=i;
rank[i]=1;
}
}
intfind(inti){
return(parent[i]==i)?i:(parent[i]=find(parent[i]));
}
voidunite(intx,inty){
ints1=find(x),s2=find(y);
if(s1!=s2){
if(rank[s1]<rank[s2])parent[s1]=s2;
elseif(rank[s1]>rank[s2])parent[s2]=s1;
elseparent[s2]=s1,rank[s1]++;
}
}
};
boolcomparator(vector<int>&a,vector<int>&b){
returna[2]<b[2];
}
intkruskalsMST(intV,vector<vector<int>>&edges){

// Sort all edges
sort(edges.begin(),edges.end(),comparator);

// Traverse edges in sorted order
DSUdsu(V);
intcost=0,count=0;

for(auto&e:edges){
intx=e[0],y=e[1],w=e[2];

// Make sure that there is no cycle
if(dsu.find(x)!=dsu.find(y)){
dsu.unite(x,y);
cost+=w;
if(++count==V-1)break;
}
}
returncost;
}
intmain(){

// An edge contains source, destination and weight
vector<vector<int>>edges={
{0,1,10},{1,3,15},{2,3,4},{2,0,6},{0,3,5}
};

cout<<kruskalsMST(4,edges);

return0;
}
C
// C code to implement Kruskal's algorithm
#include<stdio.h>
#include<stdlib.h>
// Comparator function to use in sorting
intcomparator(constintp1[],constintp2[])
{
returnp1[2]-p2[2];
}
// Initialization of parent[] and rank[] arrays
voidmakeSet(intparent[],intrank[],intn)
{
for(inti=0;i<n;i++){
parent[i]=i;
rank[i]=0;
}
}
// Function to find the parent of a node
intfindParent(intparent[],intcomponent)
{
if(parent[component]==component)
returncomponent;
returnparent[component]
=findParent(parent,parent[component]);
}
// Function to unite two sets
voidunionSet(intu,intv,intparent[],intrank[],intn)
{
// Finding the parents
u=findParent(parent,u);
v=findParent(parent,v);
if(rank[u]<rank[v]){
parent[u]=v;
}
elseif(rank[u]>rank[v]){
parent[v]=u;
}
else{
parent[v]=u;
// Since the rank increases if
// the ranks of two sets are same
rank[u]++;
}
}
// Function to find the MST
intkruskalAlgo(intn,intedge[n][3])
{
// First we sort the edge array in ascending order
// so that we can access minimum distances/cost
qsort(edge,n,sizeof(edge[0]),comparator);
intparent[n];
intrank[n];
// Function to initialize parent[] and rank[]
makeSet(parent,rank,n);
// To store the minimun cost
intminCost=0;
for(inti=0;i<n;i++){
intv1=findParent(parent,edge[i][0]);
intv2=findParent(parent,edge[i][1]);
intwt=edge[i][2];
// If the parents are different that
// means they are in different sets so
// union them
if(v1!=v2){
unionSet(v1,v2,parent,rank,n);
minCost+=wt;
}
}
returnminCost;
}
// Driver code
intmain()
{
intedge[5][3]={{0,1,10},
{0,2,6},
{0,3,5},
{1,3,15},
{2,3,4}};
printf("%d",kruskalAlgo(5,edge));
return0;
}
Java
importjava.util.Arrays;
importjava.util.Comparator;
class GfG{
publicstaticintkruskalsMST(intV,int[][]edges){

// Sort all edges based on weight
Arrays.sort(edges,Comparator.comparingInt(e->e[2]));

// Traverse edges in sorted order
DSUdsu=newDSU(V);
intcost=0,count=0;

for(int[]e:edges){
intx=e[0],y=e[1],w=e[2];

// Make sure that there is no cycle
if(dsu.find(x)!=dsu.find(y)){
dsu.union(x,y);
cost+=w;
if(++count==V-1)break;
}
}
returncost;
}
publicstaticvoidmain(String[]args){

// An edge contains, weight, source and destination
int[][]edges={
{0,1,10},{1,3,15},{2,3,4},{2,0,6},{0,3,5}
};

System.out.println(kruskalsMST(4,edges));
}
}
// Disjoint set data structure
class DSU{
privateint[]parent,rank;
publicDSU(intn){
parent=newint[n];
rank=newint[n];
for(inti=0;i<n;i++){
parent[i]=i;
rank[i]=1;
}
}
publicintfind(inti){
if(parent[i]!=i){
parent[i]=find(parent[i]);
}
returnparent[i];
}
publicvoidunion(intx,inty){
ints1=find(x);
ints2=find(y);
if(s1!=s2){
if(rank[s1]<rank[s2]){
parent[s1]=s2;
}elseif(rank[s1]>rank[s2]){
parent[s2]=s1;
}else{
parent[s2]=s1;
rank[s1]++;
}
}
}
}
Python
from functools import cmp_to_key
def comparator(a,b):
 return a[2] - b[2];
def kruskals_mst(V, edges):
 # Sort all edges
 edges = sorted(edges,key=cmp_to_key(comparator))
 
 # Traverse edges in sorted order
 dsu = DSU(V)
 cost = 0
 count = 0
 for x, y, w in edges:
 
 # Make sure that there is no cycle
 if dsu.find(x) != dsu.find(y):
 dsu.union(x, y)
 cost += w
 count += 1
 if count == V - 1:
 break
 return cost
 
# Disjoint set data structure
class DSU:
 def __init__(self, n):
 self.parent = list(range(n))
 self.rank = [1] * n
 def find(self, i):
 if self.parent[i] != i:
 self.parent[i] = self.find(self.parent[i])
 return self.parent[i]
 def union(self, x, y):
 s1 = self.find(x)
 s2 = self.find(y)
 if s1 != s2:
 if self.rank[s1] < self.rank[s2]:
 self.parent[s1] = s2
 elif self.rank[s1] > self.rank[s2]:
 self.parent[s2] = s1
 else:
 self.parent[s2] = s1
 self.rank[s1] += 1
if __name__ == '__main__':
 
 # An edge contains, weight, source and destination
 edges = [[0, 1, 10], [1, 3, 15], [2, 3, 4], [2, 0, 6], [0, 3, 5]]
 print(kruskals_mst(4, edges))
C#
// Using System.Collections.Generic;
usingSystem;
classGfG{
publicstaticintKruskalsMST(intV,int[][]edges){
// Sort all edges based on weight
Array.Sort(edges,(e1,e2)=>e1[2].CompareTo(e2[2]));

// Traverse edges in sorted order
DSUdsu=newDSU(V);
intcost=0,count=0;

foreach(vareinedges){
intx=e[0],y=e[1],w=e[2];

// Make sure that there is no cycle
if(dsu.Find(x)!=dsu.Find(y)){
dsu.Union(x,y);
cost+=w;
if(++count==V-1)break;
}
}
returncost;
}
publicstaticvoidMain(string[]args){
// An edge contains, weight, source and destination
int[][]edges={
newint[]{0,1,10},newint[]{1,3,15},newint[]{2,3,4},newint[]{2,0,6},newint[]{0,3,5}
};

Console.WriteLine(KruskalsMST(4,edges));
}
}
// Disjoint set data structure
classDSU{
privateint[]parent,rank;
publicDSU(intn){
parent=newint[n];
rank=newint[n];
for(inti=0;i<n;i++){
parent[i]=i;
rank[i]=1;
}
}
publicintFind(inti){
if(parent[i]!=i){
parent[i]=Find(parent[i]);
}
returnparent[i];
}
publicvoidUnion(intx,inty){
ints1=Find(x);
ints2=Find(y);
if(s1!=s2){
if(rank[s1]<rank[s2]){
parent[s1]=s2;
}elseif(rank[s1]>rank[s2]){
parent[s2]=s1;
}else{
parent[s2]=s1;
rank[s1]++;
}
}
}
}
JavaScript
functionkruskalsMST(V,edges){

// Sort all edges
edges.sort((a,b)=>a[2]-b[2]);

// Traverse edges in sorted order
constdsu=newDSU(V);
letcost=0;
letcount=0;
for(const[x,y,w]ofedges){

// Make sure that there is no cycle
if(dsu.find(x)!==dsu.find(y)){
dsu.unite(x,y);
cost+=w;
if(++count===V-1)break;
}
}
returncost;
}
// Disjoint set data structure
classDSU{
constructor(n){
this.parent=Array.from({length:n},(_,i)=>i);
this.rank=Array(n).fill(1);
}
find(i){
if(this.parent[i]!==i){
this.parent[i]=this.find(this.parent[i]);
}
returnthis.parent[i];
}
unite(x,y){
consts1=this.find(x);
consts2=this.find(y);
if(s1!==s2){
if(this.rank[s1]<this.rank[s2])this.parent[s1]=s2;
elseif(this.rank[s1]>this.rank[s2])this.parent[s2]=s1;
else{
this.parent[s2]=s1;
this.rank[s1]++;
}
}
}
}
constedges=[
[0,1,10],[1,3,15],[2,3,4],[2,0,6],[0,3,5]
];
console.log(kruskalsMST(4,edges));

Output
Following are the edges in the constructed MST
2 -ひく-ひく 3 == 4
0 -ひく-ひく 3 == 5
0 -ひく-ひく 1 == 10
Minimum Cost Spanning Tree: 19

Time Complexity: O(E * log E) or O(E * log V)

Auxiliary Space: O(E+V), where V is the number of vertices and E is the number of edges in the graph.

Problems based on Minimum Spanning Tree


[フレーム]
Kruskal’s Algorithm for Minimum Spanning Tree
Improve
Article Tags :

Explore

Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

AltStyle によって変換されたページ (->オリジナル) /