MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / Solution

Class Solution

KruskalsAlgorithm.java:1–29  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Solution {
2 static int spanningTree(int V, int E, List<List<int[]>> adj) {
3 // Code Here.
4 //(u, v, weight)
5 PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<>(){
6 public int compare(int pair1[], int pair2[]){
7 return pair1[2] - pair2[2];
8 }
9 });
10 // insert edges in pq
11 for(int i=0;i<V;i++){
12 for(int edges[] : adj.get(i)){
13 pq.offer(new int[]{i,edges[0],edges[1]});
14 }
15 }
16 DisjointSet dsu = new DisjointSet(V);
17 int sum=0;
18 while(!pq.isEmpty()){
19 int object[] = pq.poll();
20 int u = object[0];
21 int v = object[1];
22 int weight = object[2];
23 if(dsu.unionBySize(u,v)){
24 sum += weight;
25 }
26 }
27 return sum;
28 }
29}
30
31
32class DisjointSet {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected