I came up with the following code by following Prof. Sedgewick's lecture on Coursera.
Please review this code and let me know if there is anything that I got wrong in implementing Kruskal's algorithm. I'd also like to know what is Big-O complexity of this algorithm.
import java.util.ArrayDeque;
import java.util.PriorityQueue;
import java.util.Queue;
public class KruskalMST {
private class WeightedEdge {
public int from, to, weight;
public WeightedEdge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("From --> ");
sb.append(from+1);
sb.append(", to --> ");
sb.append(to+1);
sb.append(", weight --> ");
sb.append(weight);
return sb.toString();
}
}
private class UnionFind {
private int capacity;
private int[] arr;
private int[] size;
public UnionFind(int capacity) {
this.capacity = capacity;
this.arr = new int[capacity];
this.size = new int[capacity];
for(int i=0; i < capacity; i++) {
this.arr[i] = i;
this.size[i] = 1;
}
}
private int root(int i) {
while(i != arr[i]) {
i = arr[arr[i]];
}
return i;
}
public void union(int i, int j) {
int p = root(i);
int q = root(j);
if(p != q) {
if(this.size[p] <= this.size[q]) {
this.size[q] += this.size[p];
this.arr[p] = q;
}
else {
this.arr[q] = p;
this.size[p] += this.size[q];
}
}
}
public boolean connected(int i, int j) {
int p = root(i);
int q = root(j);
return p == q;
}
}
public Queue<WeightedEdge> findMinCostConnectionToAllCities(int[][] roadNetwork) {
int n = roadNetwork.length;
PriorityQueue<WeightedEdge> pq = new PriorityQueue<WeightedEdge>(2*n,(WeightedEdge e1, WeightedEdge e2) -> {
return e1.weight - e2.weight;
});
Queue<WeightedEdge> mst = new ArrayDeque<>();
UnionFind uf = new UnionFind(n);
for(int i=0; i < n; i++) {
for(int j=0; j < n; j++) {
if(i != j && roadNetwork[i][j] > 0) {
WeightedEdge edge = new WeightedEdge(i,j,roadNetwork[i][j]);
pq.add(edge);
}
}
}
while(!pq.isEmpty() && mst.size() < n-1) {
WeightedEdge edge = pq.remove();
if(!uf.connected(edge.from, edge.to)) {
uf.union(edge.from,edge.to);
mst.add(edge);
}
}
return mst;
}
public static void main (String[] args) {
int[][] city1 = {{0, 1, 2, 3, 4},
{1, 0, 5, 0, 7},
{2, 5, 0, 6, 0},
{3, 0, 6, 0, 0},
{4, 7, 0, 0, 0}};
int[][] city2 = {{0, 1, 1, 100, 0, 0},
{1, 0, 1, 0, 0, 0},
{1, 1, 0, 0, 0, 0},
{100, 0, 0, 0, 2, 2},
{0, 0, 0, 2, 0, 2},
{0, 0, 0, 2, 2, 0}};
KruskalMST kruskal = new KruskalMST();
Queue<WeightedEdge> mst = kruskal.findMinCostConnectionToAllCities(city2);
int totalCost = 0;
for(WeightedEdge edge: mst) {
totalCost += edge.weight;
System.out.println(edge.toString());
}
System.out.println("Total cost --> " + totalCost);
}
}