Advertisement
Aldin_SXR

LazyPrimMST.java

May 27th, 2020
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. package ds.lazy.prim;
  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.  
  8. public class LazyPrimMST {
  9.    
  10.     private boolean[] marked;   // MST vertices
  11.     private Queue<Edge> mst;    // MST edges
  12.     private MinPQ<Edge> pq;     // crossing (and ineligible) edges
  13.    
  14.     /* Perform the lazy Prim's algorithm */
  15.     public LazyPrimMST(EdgeWeightedGraph G) {
  16.         pq = new MinPQ<Edge>();
  17.         marked = new boolean[G.V()];
  18.         mst = new Queue<Edge>();
  19.        
  20.         visit(G, 0);                // start the algorithm from vertex 0
  21.         while (!pq.isEmpty()) {     // iterate over the min-queue
  22.             Edge e = pq.delMin();   // get the edge with the lowest weight
  23.             int v = e.either();     // extract one vertex
  24.             int w = e.other(v);     // extract the other vertex
  25.            
  26.             if (marked[v] && marked[w]) {   // if both vertices are already marked,
  27.                 continue;                   // skip them, as they are ineligible
  28.             }
  29.            
  30.             mst.enqueue(e);         // otherwise, add the edge to the MST
  31.             if (!marked[v]) {       // if vertex v is not in the tree,
  32.                 visit(G, v);        // move to vertex v
  33.             }
  34.             if (!marked[w]) {       // if vertex w is not in the tree,
  35.                 visit(G, w);        // move to vertex w
  36.             }
  37.         }
  38.     }
  39.    
  40.     /* Visit adjacent vertices and add them to the min-queue */
  41.     private void visit(EdgeWeightedGraph G, int v) {
  42.         marked[v] = true;                   // mark the vertex you are currently on
  43.         for (Edge e: G.adj(v)) {            // iterate over adjacent vertices
  44.             if (!marked[e.other(v)]) {      // if the other end of the edge in not in the MST
  45.                 pq.insert(e);               // insert that edge into the min-queue
  46.             }
  47.         }
  48.     }
  49.    
  50.     /* Get a list of MST edges */
  51.     public Iterable<Edge> edges() {
  52.         return mst;
  53.     }
  54.    
  55.     /* Get the weight of the MST */
  56.     public double weight() {
  57.         double total = 0;           // initialize
  58.         for (Edge e: mst) {         // iterate over all MST edges
  59.             total += e.weight();    // sum weights together
  60.         }
  61.         return total;               // output the weight
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement