-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMST.java
46 lines (42 loc) · 1.09 KB
/
MST.java
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
package com.Shubhra;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class MST
{
class NodeComparator implements Comparator<Node> {
@Override
public int compare(Node o1, Node o2)
{
if (o1.edge>o2.edge)
{
return 1;
}
else if (o1.edge<o2.edge)
{
return -1;
}
return 0;
}
}
// Prints all the nodes the tree visits to form the Minimum Spanning Tree
public void Prims(Node start, ArrayList<Node> vertices[])
{
PriorityQueue<Node> nodes = new PriorityQueue<Node>(new NodeComparator());
nodes.add(start);
start.visited = true;
while (!nodes.isEmpty())
{
Node head = nodes.poll();
System.out.println(head.val);
for (Node v:vertices[head.index])
{
if(!v.visited)
{
nodes.add(v);
v.visited = true;
}
}
}
}
}