82 lines
2.0 KiB
Java
82 lines
2.0 KiB
Java
import java.util.*;
|
|
public class kruskalMST{
|
|
static class Edge implements Comparable<Edge>{
|
|
int u,v,weight;
|
|
Edge(int u, int v, int weight){
|
|
this.u=u;
|
|
this.v = v;
|
|
this.weight = weight;
|
|
|
|
}
|
|
public int compareTo(Edge other){
|
|
return this.weight-other.weight;
|
|
}
|
|
}
|
|
static int[] parent;
|
|
|
|
static int find(int x){
|
|
if(parent[x]!=x)
|
|
parent[x] = find(parent[x]);
|
|
return parent[x];
|
|
}
|
|
|
|
static void union(int x, int y){
|
|
int rootX = find(x);
|
|
int rootY = find(y);
|
|
|
|
parent[rootY]= rootX;
|
|
}
|
|
public static void main(String[] args){
|
|
Scanner sc = new Scanner(System.in);
|
|
System.out.print("ENter number of vertices: ");
|
|
int N = sc.nextInt();
|
|
|
|
int[][] graph = new int[N][N];
|
|
|
|
System.out.println("\nEnter adjacency matrix(0 if no edge): ");
|
|
for(int i =0;i<N;i++){
|
|
for(int j =0;j<N;j++){
|
|
graph[i][j] = sc.nextInt();
|
|
}
|
|
}
|
|
List<Edge> edges = new ArrayList<>();
|
|
for(int i =0;i<N;i++){
|
|
for(int j =i+1;j<N;j++){
|
|
if(graph[i][j]!=0)
|
|
edges.add(new Edge(i,j,graph[i][j]));
|
|
}
|
|
}
|
|
Collections.sort(edges);
|
|
|
|
parent = new int[N];
|
|
for(int i = 0;i<N;i++){
|
|
parent[i]= i;
|
|
|
|
}
|
|
int totalCost = 0;
|
|
int edgeCount = 0;
|
|
|
|
System.out.println("\nEdges in MST:");
|
|
for(Edge e : edges){
|
|
int rootU = find(e.u);
|
|
int rootV = find(e.v);
|
|
if(rootU!=rootV){
|
|
System.out.println(e.u+" - "+e.v+" : "+e.weight);
|
|
totalCost+=e.weight;
|
|
union(rootU,rootV);
|
|
edgeCount++;
|
|
|
|
if(edgeCount == N-1)
|
|
break;
|
|
|
|
}
|
|
}
|
|
System.out.print("\ntotal minimum cost: "+totalCost);
|
|
sc.close();
|
|
|
|
|
|
|
|
|
|
}
|
|
}
|