Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Kruskals{
- public static void main(String args[]){
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter the size of the graph in nodes");
- int n = sc.nextInt();
- int graph[][] = new int[n][n];
- int edges[][];
- System.out.println("Enter the edges for the adjacency matrix");
- int totalEdges = sc.nextInt();
- System.out.println("Enter the weights for the adjacency matrix");
- for(int x = 0; x < n; x++){
- for(int y = 0; y < n; y++){
- graph[x][y] = sc.nextInt();
- }
- }
- edges = new int[totalEdges][3];
- int count=0;
- for(int x = 0; x < n; x++){
- for(int y = x; y < n; y++){
- if(graph[x][y] > 0){
- edges[count][0] = x+1;
- edges[count][1] = y+1;
- edges[count][2] = graph[x][y];
- System.out.println(edges[count][0]+" "+edges[count][1]+" "+edges[count][2]);
- count = count + 1;
- }
- }
- }
- Kruskals.edgeSort(edges, totalEdges);
- for(int x = 0 ; x < totalEdges; x++){
- System.out.println(edges[x][0]+" "+ edges[x][1]+" "+edges[x][2]);
- }
- }
- static void edgeSort(int edges[][], int n){
- for(int x = 0; x<n; x++){
- for(int y = x; y<n; y++){
- if(edges[x][2] > edges[y][2]){
- Kruskals.swap(edges, x, 0, y, 0);
- Kruskals.swap(edges, x, 1, y, 1);
- Kruskals.swap(edges, x, 2, y, 2);
- }
- }
- }
- }
- static void swap(int arr[][], int key1, int key2, int key3, int key4){
- int temp = arr[key1][key2];
- arr[key1][key2] = arr[key3][key4];
- arr[key3][key4] = temp;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement