|
| 1 | +package ca.mcmaster.chapter.four.graph.mstree; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.FileInputStream; |
| 5 | +import java.io.FileNotFoundException; |
| 6 | +import java.util.LinkedList; |
| 7 | +import java.util.PriorityQueue; |
| 8 | +import java.util.Queue; |
| 9 | + |
| 10 | +public class LazyPrimMST implements MST { |
| 11 | + private final EdgeWeightedGraph g; |
| 12 | + private PriorityQueue<Edge> pq; |
| 13 | + private Queue<Edge> mst; //minimum spanning tree |
| 14 | + private final boolean[] marked; //If current vertex is in the tree |
| 15 | + public LazyPrimMST(EdgeWeightedGraph g){ |
| 16 | + this.g = g; |
| 17 | + marked = new boolean[g.V()]; |
| 18 | + pq = new PriorityQueue<>(); |
| 19 | + mst = new LinkedList<Edge>(); |
| 20 | + visit(g, 0); |
| 21 | + while(!pq.isEmpty()){ |
| 22 | + Edge edge = pq.poll(); //get the smallest edge from the graph |
| 23 | + int v = edge.either(); int w = edge.other(v); |
| 24 | + if(marked[v] && marked[w]) continue; //both vertexs are in the mst |
| 25 | + mst.offer(edge); |
| 26 | + if(!marked[v]) visit(g, v); |
| 27 | + if(!marked[w]) visit(g, w); |
| 28 | + } |
| 29 | + } |
| 30 | + @Override |
| 31 | + public Iterable<Edge> edges() { |
| 32 | + return mst; |
| 33 | + } |
| 34 | + @Override |
| 35 | + public double weight() { |
| 36 | + double res = 0d; |
| 37 | + for(Edge e : mst) |
| 38 | + res += e.weight(); |
| 39 | + return res; |
| 40 | + } |
| 41 | + private void visit(EdgeWeightedGraph g, int v){ |
| 42 | + marked[v] = true; |
| 43 | + for(Edge e : g.adj(v)) |
| 44 | + if(!marked[e.other(v)]) pq.add(e); |
| 45 | + } |
| 46 | + public static void main(String[] args) throws FileNotFoundException { |
| 47 | + FileInputStream is = new FileInputStream(new File("src/ca/mcmaster/chapter/four/graph/mstree/mediumEWG.txt")); |
| 48 | + EdgeWeightedGraph graph = new EdgeWeightedGraph(is); |
| 49 | + LazyPrimMST mst = new LazyPrimMST(graph); |
| 50 | + Iterable<Edge> edges = mst.edges(); |
| 51 | + for(Edge e : edges) |
| 52 | + System.out.println(e.toString()); |
| 53 | + System.out.println("Weight: " + mst.weight()); |
| 54 | + } |
| 55 | +} |
0 commit comments