-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLazyPrimMST.java
More file actions
56 lines (37 loc) · 1.68 KB
/
LazyPrimMST.java
File metadata and controls
56 lines (37 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class LazyPrimMST {
// the lazy imp. leaves edges on the PQ, which it knows will never be used. The eager improves the space
//complexity of the algorithm. See book for more info.
private boolean[] marked; // Vertices on MST,A wayto signal which vertices are on the MST. Used by the algorithm.
private Queue<Edge> mst; // edges the comprimise the MST. This is what client usually wants to know.
private MinPQ<Edge> pq;
public LazyPrimMST(EdgeWeightedGraph G) {
marked = new boolean[G.V()];
mst = new Queue<Edge>();
pq = new MinPQ<Edge>(); // pq will rezize automatically
visit(G, 0); // we assume G is connected.
while (!pq.isEmpty()) {
Edge e = pq.delMin(); //repeatedly delete the min weight edge e = v -> w fro PQ
int v = e.either(); int w = e.other(v);
if (marked[v] && marked[w]) // ignore if both endpoints in MST
continue;
mst.enqueue(e); // add edge to MST
if (!marked[v]) visit(G,v); // we visit whichever vertex that was not on the tree
if (!marked[w]) visit(G,w); // and put it on the tree and add edges incident to it
}
}
// puts arg vertex v on mst and add all edges incident to v on the pq
private void visit(EdgeWeightedGraph G, int v) {
marked[v]=true; // add v to the tree.
for (Edge e : G.adj(v)) {
if (!marked[e.other(v)]) // for each e=v->w, add e to pq if w not already in T
pq.insert(e);
}
}
public Iterable<Edge> edges() {return mst; }
public static void main(String[] args) throws Exception {
EdgeWeightedGraph G = new EdgeWeightedGraph();
LazyPrimMST mst = new LazyPrimMST(G);
for(Edge e : mst.edges())
System.out.println(e);
}
}