MCPcopy Create free account
hub / github.com/PrajaktaSathe/Java / MST

Class MST

Programs/PrimsAlgorithm.java:8–100  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6import java.io.*;
7
8class MST {
9 // Number of vertices in the graph
10 private static final int V = 5;
11
12 // A utility function to find the vertex with minimum key
13 // value, from the set of vertices not yet included in MST
14 int minKey(int key[], Boolean mstSet[])
15 {
16 // Initialize min value
17 int min = Integer.MAX_VALUE, min_index = -1;
18
19 for (int v = 0; v < V; v++)
20 if (mstSet[v] == false && key[v] < min) {
21 min = key[v];
22 min_index = v;
23 }
24
25 return min_index;
26 }
27
28 // A utility function to print the constructed MST stored in
29 // parent[]
30 void printMST(int parent[], int graph[][])
31 {
32 System.out.println("Edge \tWeight");
33 for (int i = 1; i < V; i++)
34 System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);
35 }
36
37 // Function to construct and print MST for a graph represented
38 // using adjacency matrix representation
39 void primMST(int graph[][])
40 {
41 // Array to store constructed MST
42 int parent[] = new int[V];
43
44 // Key values used to pick minimum weight edge in cut
45 int key[] = new int[V];
46
47 // To represent set of vertices included in MST
48 Boolean mstSet[] = new Boolean[V];
49
50 // Initialize all keys as INFINITE
51 for (int i = 0; i < V; i++) {
52 key[i] = Integer.MAX_VALUE;
53 mstSet[i] = false;
54 }
55
56 // Always include first 1st vertex in MST.
57 key[0] = 0; // Make key 0 so that this vertex is
58 // picked as first vertex
59 parent[0] = -1; // First node is always root of MST
60
61 // The MST will have V vertices
62 for (int count = 0; count < V - 1; count++) {
63 // Pick thd minimum key vertex from the set of vertices
64 // not yet included in MST
65 int u = minKey(key, mstSet);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected