forked from striver79/StriversGraphSeries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KruskalAlgoJava
96 lines (80 loc) · 2.1 KB
/
KruskalAlgoJava
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.util.*;
class Node
{
private int u;
private int v;
private int weight;
Node(int _u, int _v, int _w) { u = _u; v = _v; weight = _w; }
Node() {}
int getV() { return v; }
int getU() { return u; }
int getWeight() { return weight; }
}
class SortComparator implements Comparator<Node> {
@Override
public int compare(Node node1, Node node2)
{
if (node1.getWeight() < node2.getWeight())
return -1;
if (node1.getWeight() > node2.getWeight())
return 1;
return 0;
}
}
class Main
{
private int findPar(int u, int parent[]) {
if(u==parent[u]) return u;
return parent[u] = findPar(parent[u], parent);
}
private void union(int u, int v, int parent[], int rank[]) {
u = findPar(u, parent);
v = findPar(v, parent);
if(rank[u] < rank[v]) {
parent[u] = v;
}
else if(rank[v] < rank[u]) {
parent[v] = u;
}
else {
parent[v] = u;
rank[u]++;
}
}
void KruskalAlgo(ArrayList<Node> adj, int N)
{
Collections.sort(adj, new SortComparator());
int parent[] = new int[N];
int rank[] = new int[N];
for(int i = 0;i<N;i++) {
parent[i] = i;
rank[i] = 0;
}
int costMst = 0;
ArrayList<Node> mst = new ArrayList<Node>();
for(Node it: adj) {
if(findPar(it.getU(), parent) != findPar(it.getV(), parent)) {
costMst += it.getWeight();
mst.add(it);
union(it.getU(), it.getV(), parent, rank);
}
}
System.out.println(costMst);
for(Node it: mst) {
System.out.println(it.getU() + " " +it.getV());
}
}
public static void main(String args[])
{
int n = 5;
ArrayList<Node> adj = new ArrayList<Node>();
adj.add(new Node(0, 1, 2));
adj.add(new Node(0, 3, 6));
adj.add(new Node(1, 3, 8));
adj.add(new Node(1, 2, 3));
adj.add(new Node(1, 4, 5));
adj.add(new Node(2, 4, 7));
Main obj = new Main();
obj.KruskalAlgo(adj, n);
}
}