Code:
import java.util.ArrayList;
public class Prims {
static class Vertex{
int parent;
boolean set;
int key;
public Vertex(int parent, boolean set, int key) {
this.parent = parent;
this.set = set;
this.key = key;
}
@Override public String toString() {
return "Vertex{" +
"parent=" + parent +
", set=" + set +
", key=" + key +
'}';
}
}
public static void main(String[] nt){
int graph[][]= {{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0},
};
int n=graph.length;
ArrayList<Vertex> vertices=new ArrayList<>();
for(int i=0;i<n;i++) {
vertices.add(new Vertex(-1, false, Integer.MAX_VALUE));
}
vertices.get(0).key=0;
for (int i=0;i<n;i++){
int min=find(vertices);
vertices.get(min).set=true;
for(int j=1;j<n;j++){
if(graph[min][j]<vertices.get(j).key&&vertices.get(j).set==false && graph[min][j]!=0){
vertices.get(j).key=graph[min][j];
vertices.get(j).parent=min;
}
}
}
System.out.println("Edge Weight");
for(int i=1;i<vertices.size();i++){
System.out.println(vertices.get(i).parent+" - "+i+" : "+graph[i][vertices.get(i).parent]);
//System.out.println(vertices.get(i).toString()); }
}
static int find(ArrayList<Vertex> vertices){
int min=Integer.MAX_VALUE,i=0;
for(int x=0;x<vertices.size();x++){
if(vertices.get(x).key<min && vertices.get(x).set!=true){
min=vertices.get(x).key;
i=x;
}
}
return i;
}
}
Output: