-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathPrimsAlgorithm.java
More file actions
36 lines (32 loc) · 1.13 KB
/
PrimsAlgorithm.java
File metadata and controls
36 lines (32 loc) · 1.13 KB
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
// User function Template for Java
class Solution {
static int spanningTree(int V, int E, List<List<int[]>> adj) {
// Code Here.
//(parent, node, weight)
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[2] - b[2]);
int sum=0;
ArrayList<int[]> edges = new ArrayList<>();
boolean visited[] = new boolean[V];
pq.offer(new int[]{-1,0,0});
while(!pq.isEmpty()){
int object[] = pq.poll();
int parent = object[0];
int node = object[1];
int weight = object[2];
if(visited[node]) continue;
visited[node] = true;
if(parent!=-1){
edges.add(new int[]{parent, node});
sum += weight;
}
for(int neighbourObject[] : adj.get(node)){
int neighbourNode = neighbourObject[0];
int neighbourWeight = neighbourObject[1];
if(!visited[neighbourNode]){
pq.offer(new int[]{node,neighbourNode,neighbourWeight});
}
}
}
return sum;
}
}