Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class prims{
- public static void main(String args[]){
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter the size of Graph Matrix");
- int rows = sc.nextInt();
- int columns = sc.nextInt();
- int v = rows;
- int arr[][] = new int[rows][columns];
- for(int x = 0; x < rows; x++){
- for(int y = 0; y < columns; y++){
- arr[x][y] = sc.nextInt();
- }
- }
- int parent[] = new int[v];
- int key[] = new int[v];
- Boolean mst[] = new Boolean[v];
- for(int i = 0; i < v; i++){
- key[i] =Integer.MAX_VALUE;
- mst[i] = false;
- }
- key[0] = 0;
- parent[0] = -1;
- for(int count = 0; count < v - 1; count++){
- int u = minimum_key(key, mst, v);
- mst[u] = true;
- for(int i = 0; i < v; i++){
- if(arr[u][i] !=0 && mst[i] == false && arr[u][i] < key[i]){
- parent[i] = u;
- key[i] = arr[u][i];
- }
- }
- }
- System.out.println("Edge \tWeight");
- for (int i = 1; i < v; i++)
- System.out.println(parent[i] + " - " + i + "\t" + arr[i][parent[i]]);
- }
- public static int minimum_key(int key[], Boolean mst[], int v){
- int min = Integer.MAX_VALUE, min_index = -1;
- for(int i = 0; i < v; i++){
- if (mst[i] == false && key[i] < min) {
- min = key[i];
- min_index = i;
- }
- }
- return min_index;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment