Jacob_Thomas

Prims

Jan 28th, 2021
768
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. import java.util.*;
  2. class prims{
  3.     public static void main(String args[]){
  4.         Scanner sc = new Scanner(System.in);
  5.         System.out.println("Enter the size of Graph Matrix");
  6.         int rows = sc.nextInt();
  7.         int columns = sc.nextInt();
  8.         int v = rows;
  9.         int arr[][] = new int[rows][columns];
  10.         for(int x = 0; x < rows; x++){
  11.             for(int y = 0; y < columns; y++){
  12.                 arr[x][y] = sc.nextInt();
  13.             }
  14.         }
  15.         int parent[] = new int[v];
  16.         int key[] = new int[v];
  17.         Boolean mst[] = new Boolean[v];
  18.         for(int i = 0; i < v; i++){
  19.             key[i] =Integer.MAX_VALUE;
  20.             mst[i] = false;
  21.         }
  22.         key[0] = 0;
  23.         parent[0] = -1;
  24.         for(int count = 0; count < v - 1; count++){
  25.             int u = minimum_key(key, mst, v);
  26.             mst[u] = true;
  27.             for(int i = 0; i < v; i++){
  28.                 if(arr[u][i] !=0 && mst[i] == false && arr[u][i] < key[i]){
  29.                     parent[i] = u;
  30.                     key[i] = arr[u][i];
  31.                 }
  32.             }
  33.         }
  34.        
  35.         System.out.println("Edge \tWeight");
  36.         for (int i = 1; i < v; i++)
  37.             System.out.println(parent[i] + " - " + i + "\t" + arr[i][parent[i]]);
  38.     }
  39.     public static int minimum_key(int key[], Boolean mst[], int v){
  40.         int min = Integer.MAX_VALUE, min_index = -1;
  41.         for(int i = 0; i < v; i++){
  42.             if (mst[i] == false && key[i] < min) {
  43.                 min = key[i];
  44.                 min_index = i;
  45.             }
  46.  
  47.         }
  48.         return min_index;
  49.     }
  50.    
  51. }
Advertisement
Add Comment
Please, Sign In to add comment