prims (1)
Mon Nov 18 2024 06:57:20 GMT+0000 (Coordinated Universal Time)
Saved by @wtlab
import java.util.Scanner;
class PrimsAlgorithm {
private static int V;
int minKey(int key[], boolean mstSet[]) {
int min = Integer.MAX_VALUE, minIndex = -1;
for (int v = 0; v < V; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
void printMST(int parent[], int graph[][]) {
int totalCost = 0;
System.out.println("Edge \tWeight");
for (int i = 1; i < V; i++) {
System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);
totalCost += graph[i][parent[i]];
}
System.out.println("Total cost of the MST: " + totalCost);
}
void primMST(int graph[][]) {
int parent[] = new int[V];
int key[] = new int[V];
boolean mstSet[] = new boolean[V];
for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++) {
if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
printMST(parent, graph);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of vertices: ");
V = scanner.nextInt();
int[][] graph = new int[V][V];
System.out.println("Enter the adjacency matrix (enter 0 if there is no edge between two vertices):");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
graph[i][j] = scanner.nextInt();
}
}
PrimsAlgorithm t = new PrimsAlgorithm();
t.primMST(graph);
scanner.close();
}
}
/*2 0 6 0
2 0 3 8 5
0 3 0 0 7
6 8 0 0 9
0 5 7 9 0
Edge Weight
0 - 1 2
1 - 2 3
0 - 3 6
1 - 4 5
Total cost of the MST: 16



Comments