-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJava code
60 lines (55 loc) · 1.34 KB
/
Java code
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
package datastructures;
import java.util.Arrays;
import java.util.Scanner;
class Edge implements Comparable<Edge> {
int source,dest,weight;
@Override
public int compareTo(Edge o) {
return this.weight-o.weight;
}
}
public class Kruskals {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter no. of vertices and edges");
int v=sc.nextInt();
int e=sc.nextInt();
Edge array[]=new Edge[e];
for(int i=0;i<e;i++) {
System.out.println("Enter values:");
array[i]=new Edge();
array[i].source=sc.nextInt();
array[i].dest=sc.nextInt();
array[i].weight=sc.nextInt();
}
kuruskals(array,v,e);
}
static void kuruskals(Edge[] array,int v,int e) {
Arrays.sort(array);
Edge op[]=new Edge[v-1];
int k=0;
int parent[]=new int[v];
for(int i=0;i<v;i++) {
parent[i]=i;
}
for(int i=0;i<e;i++) {
if(k==v-1) break;
Edge curr=array[i];
int src=find(curr.source,parent);
int dest=find(curr.dest,parent);
if(src!=dest) {
op[k]=curr;
k++;
parent[src]=dest;
}
}
for(int i =0; i <op.length; i++)
System.out.println(op[i].source + " ->" + op[i].dest + " ->" + op[i].weight);
}
static int find(int s,int[] parent) {
if(parent[s]==s) {
return s;
}
return find(parent[s],parent);
}
}