-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimMST.java
More file actions
76 lines (69 loc) · 2.07 KB
/
PrimMST.java
File metadata and controls
76 lines (69 loc) · 2.07 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.Random;;
public class PrimMST{
private boolean[] marked;
private Edge[] edgeTo;
private double[] distTo;
private IndexMinPQ<Double> pq;
public PrimMST(EdgeWeightGraph G){
marked=new boolean[G.V()];
edgeTo=new Edge[G.V()];
distTo=new double[G.V()];
pq=new IndexMinPQ<>(G.V());
for (int i=0;i<G.V();i++){
distTo[i]=Double.POSITIVE_INFINITY;
}
distTo[0]=0.0;
pq.insert(0, 0.0);
while (!pq.isEmpty()){visit(G,pq.delMin());}
}
private void visit(EdgeWeightGraph G, int v){
marked[v]=true;
for (Edge edge:G.adj(v)){
int w=edge.other(v);
if (marked[w]) continue;
if (edge.weight()<distTo[w]){
distTo[w]=edge.weight();
edgeTo[w]=edge;
if (pq.contains(w)) pq.replace(w,distTo[w]);
else pq.insert(w, distTo[w]);
}
}
}
public Iterable<Edge> edges(){
Queue<Edge> queue=new Queue<>();
for (int i=0;i<edgeTo.length;i++){
if (edgeTo[i]==null) continue;
queue.enqueue(edgeTo[i]);
}
return queue;
}
public String showMinTree(){
String s="";
for (Edge edge:this.edges()){
s+=edge+"\n";
}
return s;
}
public double weight(){
double weight=0.0;
for (Edge edge:this.edges()){
weight+=edge.weight();
}
return weight;
}
public static void main(String[] args){
Random r = new Random();
int V=10;
EdgeWeightGraph g=new EdgeWeightGraph(V);
for (int i=0;i<2*V;i++){
int w=r.nextInt(V-1);
int v=r.nextInt(V-1);
double weight=r.nextDouble();
Edge edge=new Edge(w,v,weight);
g.addEdge(edge);
}
PrimMST prim=new PrimMST(g);
System.out.println(prim.showMinTree());
System.out.println(prim.weight());
}
}