-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskalMST.java
More file actions
37 lines (27 loc) · 760 Bytes
/
KruskalMST.java
File metadata and controls
37 lines (27 loc) · 760 Bytes
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
public class KruskalMST {
private Queue<Edge> mst = new Queue<Edge>();
public KruskalMST(EdgeWeightedGraph G)
{
MinPQ<Edge> pq = new MinPQ<Edge>();
for (Edge e : G.edges())
pq.insert(e);
UF uf = new UF(G.V());
while (!pq.isEmpty() && mst.size() < (G.V()-1))
{
Edge e = pq.delMin();
int v = e.either(), w = e.other(v);
if(!uf.connected(v,w)) // add edge to mst as long as no cycle is created
{
uf.union(v,w);
mst.enqueue(e);
}
}
}
public Iterable<Edge> edges() { return mst; }
public static void main(String[] args) throws Exception {
EdgeWeightedGraph G = new EdgeWeightedGraph();
KruskalMST mst = new KruskalMST(G);
for(Edge e : mst.edges())
System.out.println(e);
}
}