-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraphs-2: Kruskal's Algorithm
72 lines (63 loc) · 2.03 KB
/
Graphs-2: Kruskal's Algorithm
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
import java.util.Scanner;
import java.util.Arrays;
class Edge implements Comparable<Edge>{
int source;
int destination;
int weight;
public int compareTo(Edge o){
return this.weight-o.weight;
// if(this.weight>o.weight)
// return 1;
// else if(this.weight<o.weight)
// return -1;
// else
// return 0;
}
}
public class Solution {
public static void kruskals(Edge input[],int V){
Arrays.sort(input);
int count=0;
int k=0;
Edge output[]=new Edge[V-1];
int parent[]=new int[V];
for(int j=0;j<V;j++){
parent[j]=j;
}
while(count!=V-1){
Edge currentEdge=input[k];
int sourceparent=parentcall(parent,currentEdge.source);
int destinationparent=parentcall(parent,currentEdge.destination);
if(sourceparent!=destinationparent)
{
output[count]=currentEdge;
count++;
parent[sourceparent]=destinationparent;
}
k++;
}
for(int i=0;i<V-1;i++){
if(output[i].source<=output[i].destination)
System.out.println(output[i].source+" "+output[i].destination+" "+output[i].weight);
else
System.out.println(output[i].destination+" "+output[i].source+" "+output[i].weight);
}
}
public static int parentcall(int[] parent,int vertex){
if(vertex==parent[vertex])
return vertex;
return parentcall(parent,parent[vertex]);
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int V = s.nextInt();
int E = s.nextInt();
Edge input[]=new Edge[E];
for(int i=0;i<input.length;i++){
input[i]= new Edge();
input[i].source=s.nextInt();
input[i].destination=s.nextInt();
input[i].weight=s.nextInt();
}
kruskals(input,V);
}}