Advertisement
Jacob_Thomas

Kruskals

Jan 28th, 2021
841
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. import java.util.*;
  2. class Kruskals{
  3.     public static void main(String args[]){
  4.         Scanner sc = new Scanner(System.in);
  5.         System.out.println("Enter the size of the graph in nodes");
  6.         int n = sc.nextInt();
  7.         int graph[][] = new int[n][n];
  8.         int edges[][];
  9.         System.out.println("Enter the edges for the adjacency matrix");
  10.         int totalEdges = sc.nextInt();
  11.         System.out.println("Enter the weights for the adjacency matrix");
  12.         for(int x = 0; x < n; x++){
  13.             for(int y = 0; y < n; y++){
  14.                graph[x][y] = sc.nextInt();
  15.             }
  16.         }
  17.         edges = new int[totalEdges][3];
  18.         int count=0;
  19.         for(int x = 0; x < n; x++){
  20.             for(int y = x; y < n; y++){
  21.                 if(graph[x][y] > 0){
  22.                     edges[count][0] = x+1;
  23.                     edges[count][1] = y+1;
  24.                     edges[count][2] = graph[x][y];
  25.                     System.out.println(edges[count][0]+" "+edges[count][1]+" "+edges[count][2]);
  26.                     count = count + 1;
  27.  
  28.                 }
  29.                
  30.             }
  31.         }
  32.         Kruskals.edgeSort(edges, totalEdges);
  33.         for(int x = 0 ; x < totalEdges; x++){
  34.             System.out.println(edges[x][0]+" "+ edges[x][1]+" "+edges[x][2]);
  35.         }
  36.     }
  37.     static void edgeSort(int edges[][], int n){
  38.         for(int x = 0; x<n; x++){
  39.             for(int y = x; y<n; y++){
  40.                 if(edges[x][2] > edges[y][2]){
  41.                     Kruskals.swap(edges, x, 0, y, 0);
  42.                     Kruskals.swap(edges, x, 1, y, 1);
  43.                     Kruskals.swap(edges, x, 2, y, 2);
  44.                 }
  45.             }
  46.         }
  47.     }
  48.     static void swap(int arr[][], int key1, int key2, int key3, int key4){
  49.         int temp = arr[key1][key2];
  50.         arr[key1][key2] = arr[key3][key4];
  51.         arr[key3][key4] = temp;
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement