import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
class KaushikKruskalAlgorithm
{
private List<Edge> edges;
private int numberOfVertices;
public static final int MAX_VALUE = 999;
public KaushikKruskalAlgorithm(int numberOfVertices)
{
this.numberOfVertices = numberOfVertices;
edges = new LinkedList<Edge>();
}
public void kruskalAlgorithm()
{
HashMap
<Integer,Boolean
> vistedNodes
= new HashMap
<Integer,Boolean
>(); List<Edge> selectedEdges = new ArrayList<Edge>();
boolean finished = false;
// Collections.sort(edges, new EdgeComparator());
for (Edge edge : edges)
{
if (vistedNodes.get(edge.sourcevertex)==null || vistedNodes.get(edge.destinationvertex)==null){
// Either of node is not covered. So use this edge
selectedEdges.add(edge);
vistedNodes.
put(edge.
sourcevertex,
Boolean.
TRUE); vistedNodes.
put(edge.
destinationvertex,
Boolean.
TRUE); }
}
System.
out.
println("The spanning tree is "); for (Edge edge : selectedEdges){
System.
out.
println("Between node "+edge.
sourcevertex +" & node "+edge.
destinationvertex +" weight "+edge.
weight); }
}
public static void main
(String[] args
) {
int adjacency_matrix[][];
int number_of_vertices;
Scanner scan
= new Scanner
(System.
in); System.
out.
println("Enter the number of vertices"); number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
KaushikKruskalAlgorithm kruskalAlgorithm = new KaushikKruskalAlgorithm(number_of_vertices);
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = i+1; j <= number_of_vertices; j++)
{
System.
out.
println("Enter distance between node "+ i
+" and "+j
); int weight = scan.nextInt();
if(weight!=0){
Edge edge = new Edge();
edge.sourcevertex = i;
edge.destinationvertex = j;
edge.weight = weight;
kruskalAlgorithm.edges.add(edge);
}
}
}
kruskalAlgorithm.kruskalAlgorithm();
scan.close();
}
}
class Edge implements Comparable<Edge>
{
int sourcevertex;
int destinationvertex;
int weight;
@Override
public int compareTo(Edge edge2) {
if (this.weight < edge2.weight)
return -1;
if (this.weight > edge2.weight)
return 1;
return 0;
}
}