classSolution{publicintminCostConnectPoints(int[][] points){// {weight, index}PriorityQueue<int[]> pq =newPriorityQueue<>((a, b)-> a[0]- b[0]);
pq.offer(newint[]{0,0});// Amount of pointsint n = points.length;Set<Integer> visited =newHashSet<>();int res =0;// Total costwhile(visited.size()< n){int[] arr = pq.poll();int weight = arr[0];int currNode = arr[1];// Skip if existsif(visited.contains(currNode))continue;
visited.add(currNode);
res += weight;// Adding other nodes that haven't been visited to the queuefor(int nextNode =0; nextNode < n;++nextNode){if(!visited.contains(nextNode)){int nextWeight =Math.abs(points[nextNode][0]- points[currNode][0])+Math.abs(points[nextNode][1]- points[currNode][1]);
pq.offer(newint[]{nextWeight, nextNode});}}}return res;}}
Kruskal’s
classSolution{int[] father =newint[1000];publicintminCostConnectPoints(int[][] points){int n = points.length;// Init. fathersfor(int i =0; i < n;++i){
father[i]= i;}// Min heapPriorityQueue<int[]> pq =newPriorityQueue<>((a, b)-> a[0]- b[0]);for(int i =0; i < n;++i){for(int j = i +1; j < n;++j){int dis =Math.abs(points[i][0]- points[j][0])+Math.abs(points[i][1]- points[j][1]);// Adding weight, start, end point
pq.offer(newint[]{ dis, i, j });}}int res =0;int count =1;while(count < n){int[] edge = pq.poll();int a = edge[1];int b = edge[2];int dis = edge[0];// When a and b haven't connectedif(findFather(a)!=findFather(b)){Union(a, b);++count;
res += dis;if(count == n)break;}}return res;}privateintfindFather(int x){// Itself's father should be itself// if not, find again through it's fatherif(father[x]!= x)
father[x]=findFather(father[x]);return father[x];}privatevoidUnion(int x,int y){
x = father[x];
y = father[y];// Make them the same fatherif(x < y)
father[y]= x;else
father[x]= y;}}