-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathprimsAlgoOptimised.java
More file actions
38 lines (29 loc) · 957 Bytes
/
Copy pathprimsAlgoOptimised.java
File metadata and controls
38 lines (29 loc) · 957 Bytes
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
package Graphs;
import java.util.*;
public class primsAlgoOptimised {
public static void primsOptimised(ArrayList<ArrayList<Node>> adj,int N){
int key[]=new int[N];
int parent[]=new int[N];
boolean mstSet[]=new boolean[N];
for(int i=0;i<N;i++){
key[i]=Integer.MAX_VALUE;
}
key[0]=0;
parent[0]=-1;
PriorityQueue<Node> pq=new PriorityQueue<>(N,new Node());
pq.add(new Node(key[0],0));
for(int i=0;i<N-1;i++){
int u=pq.poll().getV();
mstSet[u]=true;
for(Node it: adj.get(u)){
if(mstSet[it.getV()]==false && it.getWeight()<key[it.getV()]){
key[it.getV()]=it.getWeight();
pq.add(new Node(it.getV(),key[it.getV()]));
}
}
}
for(int i=1;i<N;i++){
System.out.println(parent[i] + " - "+ i);
}
}
}