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