Java Program to Find Minimum Spanning Tree using Prim’s Algorithm

This Java program is to find MST using Prim’s algorithm.In computer science, Prim’s algorithm is a greedy algorithm that finds a minimum spanning tree for a connected weighted undirected graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.

Here is the source code of the Java program to find MST using prim’s algorithm. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. import java.util.InputMismatchException;
  2. import java.util.Scanner;
  3.  
  4. public class Prims
  5. {
  6.     private boolean unsettled[];
  7.     private boolean settled[];
  8.     private int numberofvertices;
  9.     private int adjacencyMatrix[][];
  10.     private int key[];
  11.     public static final int INFINITE = 999;
  12.     private int parent[];
  13.  
  14.     public Prims(int numberofvertices)
  15.     {
  16.         this.numberofvertices = numberofvertices;
  17.         unsettled = new boolean[numberofvertices + 1];
  18.         settled = new boolean[numberofvertices + 1];
  19.         adjacencyMatrix = new int[numberofvertices + 1][numberofvertices + 1];
  20.         key = new int[numberofvertices + 1];
  21.         parent = new int[numberofvertices + 1];
  22.     }
  23.  
  24.     public int getUnsettledCount(boolean unsettled[])
  25.     {
  26.         int count = 0;
  27.         for (int index = 0; index < unsettled.length; index++)
  28.         {
  29.             if (unsettled[index])
  30.             {
  31.                 count++;
  32.             }
  33.         }
  34.         return count;
  35.     }
  36.  
  37.     public void primsAlgorithm(int adjacencyMatrix[][])
  38.     {
  39.         int evaluationVertex;
  40.         for (int source = 1; source <= numberofvertices; source++)
  41.         {
  42.             for (int destination = 1; destination <= numberofvertices; destination++)
  43.             {
  44.                 this.adjacencyMatrix[source][destination] = adjacencyMatrix[source][destination];
  45.             }
  46.         }
  47.  
  48.         for (int index = 1; index <= numberofvertices; index++)
  49.         {
  50.             key[index] = INFINITE;
  51.         }
  52.         key[1] = 0;
  53.         unsettled[1] = true;
  54.         parent[1] = 1;
  55.  
  56.         while (getUnsettledCount(unsettled) != 0)
  57.         {
  58.             evaluationVertex = getMimumKeyVertexFromUnsettled(unsettled);
  59.             unsettled[evaluationVertex] = false;
  60.             settled[evaluationVertex] = true;
  61.             evaluateNeighbours(evaluationVertex);
  62.         }
  63.     } 
  64.  
  65.     private int getMimumKeyVertexFromUnsettled(boolean[] unsettled2)
  66.     {
  67.         int min = Integer.MAX_VALUE;
  68.         int node = 0;
  69.         for (int vertex = 1; vertex <= numberofvertices; vertex++)
  70.         {
  71.             if (unsettled[vertex] == true && key[vertex] < min)
  72.             {
  73.                 node = vertex;
  74.                 min = key[vertex];
  75.             }
  76.         }
  77.         return node;
  78.     }
  79.  
  80.     public void evaluateNeighbours(int evaluationVertex)
  81.     {
  82.  
  83.         for (int destinationvertex = 1; destinationvertex <= numberofvertices; destinationvertex++)
  84.         {
  85.             if (settled[destinationvertex] == false)
  86.             {
  87.                 if (adjacencyMatrix[evaluationVertex][destinationvertex] != INFINITE)
  88.                 {
  89.                     if (adjacencyMatrix[evaluationVertex][destinationvertex] < key[destinationvertex])
  90.                     {
  91.                         key[destinationvertex] = adjacencyMatrix[evaluationVertex][destinationvertex];
  92.                         parent[destinationvertex] = evaluationVertex;
  93.                     }
  94.                     unsettled[destinationvertex] = true;
  95.                 }
  96.             }
  97.         }
  98.     }
  99.  
  100.     public void printMST()
  101.     {
  102.         System.out.println("SOURCE  : DESTINATION = WEIGHT");
  103.         for (int vertex = 2; vertex <= numberofvertices; vertex++)
  104.         {
  105.             System.out.println(parent[vertex] + "\t:\t" + vertex +"\t=\t"+ adjacencyMatrix[parent[vertex]][vertex]);
  106.         }
  107.     }
  108.  
  109.     public static void main(String... arg)
  110.     {
  111.         int adjacency_matrix[][];
  112.         int number_of_vertices;
  113.         Scanner scan = new Scanner(System.in);
  114.  
  115.         try
  116.         {
  117.             System.out.println("Enter the number of vertices");
  118.             number_of_vertices = scan.nextInt();
  119.             adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
  120.  
  121.             System.out.println("Enter the Weighted Matrix for the graph");
  122.             for (int i = 1; i <= number_of_vertices; i++)
  123.             {
  124.                 for (int j = 1; j <= number_of_vertices; j++)
  125.                 {
  126.                     adjacency_matrix[i][j] = scan.nextInt();
  127.                     if (i == j)
  128.                     {
  129.                         adjacency_matrix[i][j] = 0;
  130.                         continue;
  131.                     }
  132.                     if (adjacency_matrix[i][j] == 0)
  133.                     {
  134.                         adjacency_matrix[i][j] = INFINITE;
  135.                     }
  136.                 }
  137.             }
  138.  
  139.             Prims prims = new Prims(number_of_vertices);
  140.             prims.primsAlgorithm(adjacency_matrix);
  141.             prims.printMST();
  142.  
  143.         } catch (InputMismatchException inputMismatch)
  144.         {
  145.             System.out.println("Wrong Input Format");
  146.         }
  147.         scan.close();
  148.     }
  149. }


$javac Prims.java
$java Prims
 
Enter the number of vertices
5
Enter the Weighted Matrix for the graph
0 4 0 0 5
4 0 3 6 1 
0 3 0 6 2
0 6 6 0 7
5 1 2 7 0
SOURCE  : DESTINATION   =    WEIGHT
1       :      2        =       4
5       :      3        =       2
2       :      4        =       6
2       :      5        =       1

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.