-
Notifications
You must be signed in to change notification settings - Fork 0
/
Kruskal.java
54 lines (51 loc) · 1.57 KB
/
Kruskal.java
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
import java.util.Scanner;
public class Kruskal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Number of nodes :");
int n=input.nextInt();
System.out.println("Enter the Adjacency Matrix :");
int[][] matrix =new int[n][n];
int[] parent = new int[n];
int min;
int u=0;
int v=0;
int noOfEdges = 1;
int total =0;
for (int i = 0; i < n ; i++) {
parent[i]=0;
for (int j = 0; j < n ; j++) {
matrix[i][j]=input.nextInt();
if (matrix[i][j] == 0) {
matrix[i][j]=999;
}
}
}
while(noOfEdges<n){
min=999;
for (int i = 0; i < n ; i++) {
for (int j = 0; j < n ; j++) {
if (matrix[i][j] < min) {
min = matrix[i][j];
u=i;
v=j;
}
}
}
while (parent[u]!=0){
u=parent[u];
}
while (parent[v]!=0){
v=parent[v];
}
if(v!=u){
noOfEdges++;
System.out.println("Edge :"+u+" -- "+v+" Min: "+min);
total+=min;
parent[v]=u;
}
matrix[u][v]=matrix[v][u]=999;
}
System.out.println("The Weight of Minimum Spanning Tree : "+total);
}
}