Aldin_SXR

KruskalMST.java

May 28th, 2020 (edited)
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. package week13;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.PriorityQueue;
  5.  
  6. public class KruskalMST {
  7.     private ArrayList<Edge> mst;    // MST edges
  8.  
  9.     /* Perform the Kruskal's algorithm */
  10.     public KruskalMST(EdgeWeightedGraph G) {
  11.         mst = new ArrayList<>();
  12.         PriorityQueue<Edge> pq = new PriorityQueue<>();
  13.  
  14.         /* Add all edges to the MST */
  15.         for (Edge e: G.edges()) {
  16.             pq.add(e);
  17.         }
  18.  
  19.         // Union-Find data structure - helper structure to
  20.         // check if cycles exist in a graph
  21.         // UnionFind will have V elements
  22.         UnionFind uf = new UnionFind(G.V());
  23.  
  24.         while (!pq.isEmpty() && mst.size() < G.V() - 1) {
  25.             // Get minimum weight edge on priority queue
  26.             Edge e = pq.poll();     // get the edge with the lowest weight
  27.             int v = e.either();     // extract one vertex
  28.             int w = e.other(v);     // extract the other vertex
  29.  
  30.             if (uf.connected(v, w)) {   // if the edge forms a cycle,
  31.                 continue;               // ignore it
  32.             }
  33.             uf.union(v, w); // Mark two vertices as connected
  34.             mst.add(e);     // add edge to MST
  35.         }
  36.     }
  37.  
  38.     /* Get a list of MST edges */
  39.     public Iterable<Edge> edges() {
  40.         return mst;
  41.     }
  42.  
  43.     /* Get the weight of the MST */
  44.     public double weight() {
  45.         double total = 0;           // initialize
  46.         for (Edge e: mst) {         // iterate over all MST edges
  47.             total += e.weight();    // sum weights together
  48.         }
  49.         return total;               // output the weight
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment