Skip to content

Commit

Permalink
Added Kruskal Algo in Java
Browse files Browse the repository at this point in the history
  • Loading branch information
Jitendra227 committed Oct 2, 2021
1 parent 55030e2 commit 87cafcd
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions CONTRIBUTERS.MD
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,4 @@
| Rohit Amrutkar | [@rohitamrutkar1204](https://github.com/rohitamrutkar1204) | 1 |
| Ritik Kumar | [@srivastavaritik](https://github.com/srivastavaritik) | 1 |
| Surjyanee Halder | [@surjyaneeh](https://github.com/surjyaneeh) | 1 |
| Jitendra Kumar Mishra| [@jitendra227](https://github.com/jitendra227) | 1 |
54 changes: 54 additions & 0 deletions Java/KruskalAlgo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@

import java.util.Scanner;

class MstKruskal { //mst -> minimum spanning tree
void kruskal(int cost[][], int n){
int [] par = new int[n];
for(int i=0;i<n;i++){
par[i]= -1;
}
int a=0, b=0, u=0, v=0, mincost=0, min, ne =0;
System.out.println("MST edges are: ");
while(ne < n-1) {
min = 999;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(cost[i][j]< min){
min = cost[i][j];
a=u=i;
b=v=j;
}
}
}
while(par[u]!= -1)
u = par[u];
if(u!=v) {
System.out.println("from vertex "+a+" to vertex "+b+" and the cost = "+min);
System.out.println(a+"----->"+b+" with cost= "+min);
mincost+=min;
par[b] = a;
ne++;
}
cost[a][b] = cost[b][a] = 999;
}
System.out.println("cost of mst = "+mincost);
}
}
public class KruskalAlgo {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of vertices: ");
int n = s.nextInt();
int c[][] = new int[n][n];
System.out.println("Enter the cost of matrix: ");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
c[i][j] = s.nextInt();
}
}
System.out.println("Enter the source node: ");
int source = s.nextInt();
MstKruskal obj = new MstKruskal();
obj.kruskal(c, n);
}
}

0 comments on commit 87cafcd

Please sign in to comment.