|
| 1 | +public class Main { |
| 2 | + public static void main(String[] args) { |
| 3 | + int noOfVertices = 5; |
| 4 | + int startVertex=0; // A is start vertex |
| 5 | + |
| 6 | + List<Pair<Integer,Integer>>[] adj=new ArrayList[noOfVertices]; |
| 7 | + |
| 8 | + //Pair(vertex, weight) |
| 9 | + List<Pair<Integer,Integer>> list=new ArrayList<>(); |
| 10 | + list.add(new Pair(1,4)); |
| 11 | + list.add(new Pair(2,1)); |
| 12 | + adj[0]=list; |
| 13 | + |
| 14 | + list=new ArrayList<>(); |
| 15 | + list.add(new Pair(0,4)); |
| 16 | + list.add(new Pair(2,2)); |
| 17 | + list.add(new Pair(4,4)); |
| 18 | + adj[1]=list; |
| 19 | + |
| 20 | + list=new ArrayList<>(); |
| 21 | + list.add(new Pair(0,1)); |
| 22 | + list.add(new Pair(1,2)); |
| 23 | + list.add(new Pair(3,4)); |
| 24 | + adj[2]=list; |
| 25 | + |
| 26 | + list=new ArrayList<>(); |
| 27 | + list.add(new Pair(2,4)); |
| 28 | + list.add(new Pair(4,4)); |
| 29 | + adj[3]=list; |
| 30 | + |
| 31 | + list=new ArrayList<>(); |
| 32 | + list.add(new Pair(1,4)); |
| 33 | + list.add(new Pair(3,4)); |
| 34 | + adj[4]=list; |
| 35 | + |
| 36 | + int[] path = new int[noOfVertices]; |
| 37 | + Pair<Integer,Integer>[] distance = new Pair[noOfVertices]; |
| 38 | + boolean[] mstset = new boolean[noOfVertices]; |
| 39 | + |
| 40 | + // Intialize distance array |
| 41 | + for(int i=0;i<noOfVertices;i++){ |
| 42 | + distance[i] = new Pair<Integer,Integer>(i,Integer.MAX_VALUE); |
| 43 | + } |
| 44 | + |
| 45 | + distance[startVertex]=new Pair<>(startVertex,0); // Making distance for start vertex 0 |
| 46 | + path[startVertex]=startVertex; // Updating path for start vertex to itself |
| 47 | + |
| 48 | + PriorityQueue<Pair<Integer,Integer>> q=new PriorityQueue<>((a,b) -> a.getValue()-b.getValue()); |
| 49 | + q.add(distance[startVertex]); |
| 50 | + |
| 51 | + while(!q.isEmpty()){ |
| 52 | + Pair<Integer,Integer> vertexPair=q.remove(); |
| 53 | + Integer vertex=vertexPair.getKey(); |
| 54 | + mstset[vertex]=true; |
| 55 | + |
| 56 | + List<Pair<Integer,Integer>> adjVertices=adj[vertex]; |
| 57 | + |
| 58 | + for(Pair<Integer,Integer> adjPair: adjVertices){ |
| 59 | + int adjVertex=adjPair.getKey(); |
| 60 | + int weight=adjPair.getValue(); |
| 61 | + |
| 62 | + int newDistance=distance[vertex].getValue() + weight; |
| 63 | + if(!mstset[adjVertex] && distance[adjVertex].getValue() > newDistance){ |
| 64 | + q.remove(distance[adjVertex]); |
| 65 | + distance[adjVertex]=new Pair<>(adjVertex,newDistance); |
| 66 | + path[adjVertex]=vertex; |
| 67 | + q.add(distance[adjVertex]); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + System.out.println("MST formed by edges :"); |
| 73 | + for(int i=0;i<noOfVertices; i++){ |
| 74 | + if(i!=startVertex) |
| 75 | + System.out.println((char)(i+'A')+" - "+(char)(path[i]+'A')); |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments