Professional Documents
Culture Documents
javaApp;
import java.util.*;
int k=0;
for(int i=0;i<v;i++){
for(int j=0;j<i;j++){
if(graph[i][j]!=0){
k++;
}
}
}
// prims(graph);
Arrays.fill(parent,-1);
Arrays.fill(distance,Integer.MAX_VALUE);
Arrays.fill(visited,false);
distance[0]=0;
for(int i=1;i<v-1;i++){
int minValue = findMinimumValue(distance,visited);
visited[minValue]=true;
for(int j=0;j<v;j++){
if(graph[minValue][j]!=0 && visited[j]==false &&
graph[minValue][j]<distance[j]){
parent[j] = minValue;
distance[j]=graph[minValue][j];
}
}
// System.out.println(parent[minValue] +" "+ minValue +" "+
distance[minValue]);
}
// Kruskal's Algorithm
@Override
public int compareTo(edge newEdge) {
return this.weight-newEdge.weight;
}
}
Arrays.sort(edges);
// for(int i=0;i<edges.length;i++){
// System.out.println(edges[i].source +" "+ edges[i].destination +"
"+ edges[i].weight);
// }
for(int i=0;i<v;++i){
subsets[i].parent=i;
subsets[i].rank=0;
// System.out.println(i +""+ subsets[i].parent +""+
subsets[i].rank);
}
int i = 0;
int count = 0;
edge[] result = new edge[v];
while(count<v-1){
edge currentEdge = edges[i];
int xRoot = findParent(subsets,currentEdge.source);
int yRoot = findParent(subsets,currentEdge.destination);
if(xRoot != yRoot){
result[count]= currentEdge;
union(subsets,xRoot,yRoot);
count++;
}
i++;
}
int minCost=0;
for(int n=0;n<count;n++){
System.out.println(result[n].source +" -> "+
result[n].destination +" = "+ result[n].weight);
minCost+=result[n].weight;
}
System.out.println("Cost of minimum spanning tree "+ minCost);
}
}