-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskals
More file actions
95 lines (81 loc) · 2.7 KB
/
Kruskals
File metadata and controls
95 lines (81 loc) · 2.7 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
public class Edge implements Comparable<Edge>{
int v, w;
double weight;
public Edge(int v, int w, double weight){
if(v < 0) throw new IllegalArgumentException("vertex index must be a nonnegative integer");
if(w < 0) throw new IllegalArgumentException("vertex index must be a nonnegative integer");
if(Double.isNaN(weight)) throw new IllegalArgumentException("Weight is NaN");
this.v = v;
this.w = w;
this.weight = weight;
}
public double weight(){
return weight;
}
public int either(){
return v;
}
public int other(int vertex){
if(vertex == v) return w;
else if(vertex == w) return v;
else throw new IllegalArgumentException("Illegal endpoint");
}
@Override
public int compareTo(Edge that){
return Double.compare(this.weight, that.weight);
}
}
public int findParent(int[] parent, int node){
if(parent[node] != node)
return findParent(parent, parent[node]);
return node;
}
public class Node{
int id;
List<Node> adj;
int distance = 0;
public Node(int id){
this.id = id;
this.adj = new LinkedList<>();
}
public void addAdjNode(Node adj){
this.adj.add(adj);
}
}
public class EdgeWeightedGraph{
public EdgeWeightedGraph(){
}
}
public int kruskals(int gNodes, List<Integer> gFrom, List<Integer> gTo, List<Integer> gWeight){
List<Edge> edges = new ArrayList<Edge>();
Map<Integer, Integer> mapSourceIndex = new HashMap<Integer, Integer>();
for (int i = 0; i < gNodes; i++) {
if(gFrom.get(i) != gTo.get(i))
if(mapSourceIndex != null && mapSourceIndex.containsKey(gFrom.get(i))){
int previousIndex = mapSourceIndex.get(gFrom.get(i));
//if(gTo.get(previousIndex) != gTo.get(i) && gWeight.get(i) < gWeight.get(previousIndex)){
edges.add( new Edge(gFrom.get(i),gTo.get(i), gWeight.get(i)));
mapSourceIndex.put(gFrom.get(i), i);
//}
}else{
edges.add(new Edge(gFrom.get(i),gTo.get(i), gWeight.get(i)));
mapSourceIndex.put(gFrom.get(i), i);
}
}
Collections.sort(edges);
int[] parent = new int[gNodes];
for (int i = 0; i < gNodes; i++) {
parent[i] = i;
}
int output = 0;
for (int i = 0; i < edges.size(); i++) {
Edge edge = edges.get(i);
int x = findParent(parent, edge.v);
int y = findParent(parent, edge.w);
if(x != y){
output+=edge.weight;
parent[y] = x;
}
}
return output;
}