Advertisement
Aldin_SXR

KruskalMST.java

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