forked from Kraken-ops/Hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskalsAlgorithm.java
More file actions
82 lines (70 loc) · 1.86 KB
/
Copy pathKruskalsAlgorithm.java
File metadata and controls
82 lines (70 loc) · 1.86 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
import java.util.Scanner;
import java.util.*;
class Edge implements Comparable<Edge>
{
int source;
int dest;
int weight;
public int compareTo(Edge o)
{
return this.weight-o.weight;
}
}
public class Solution {
public static int findParent(int v, int parent[])
{
if(parent[v]==v)
return v;
return findParent(parent[v],parent);
}
public static void kruskal(Edge input[], int n)
{
Arrays.sort(input);
Edge[] output=new Edge[n-1];
int parent[]=new int[n];
for(int i=0;i<n;i++)
{
parent[i]=i;
}
int count=0;
int i=0;
while(count!=n-1)
{
Edge currentEdge=input[i];
int sourceParent = findParent(currentEdge.source,parent);
int destParent= findParent(currentEdge.dest,parent);
if(sourceParent!=destParent)
{
output[count]=currentEdge;
count++;
parent[sourceParent]=destParent;
}
i++;
}
for(int j=0;j<n-1;j++)
{
if(output[j].source>output[j].dest)
System.out.println(output[j].dest +" "+ output[j].source +" "+ output[j].weight);
else
System.out.println(output[j].source +" "+ output[j].dest +" "+ output[j].weight);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int V = sc.nextInt();
int E = sc.nextInt();
Edge[] input=new Edge[E];
for(int i=0;i<E;i++)
{
input[i]=new Edge();
input[i].source=sc.nextInt();
input[i].dest=sc.nextInt();
input[i].weight=sc.nextInt();
}
kruskal(input,V);
/* Write Your Code Here
* Complete the Rest of the Program
* You have to take input and print the output yourself
*/
}
}