Prim’s algorithm is a greedy
method for finding a Minimum Spanning Tree (MST) in a weighted, undirected graph. An MST
is a subset of the graph’s edges that connects all vertices together without any cycles and with the minimum possible total edge weight.
The algorithm always picks the next minimum edge that expands the growing tree, ensuring that the total weight remains as low as possible.
Consider a graph with 5 vertices labeled A, B, C, D, and E with the following weighted edges:
Step-by-Step Process:
Final MST:
Prim’s Algorithm builds a minimum spanning tree by starting from an arbitrary vertex and, at each step, adding the least expensive edge that connects a vertex in the tree to a vertex outside it. This process continues until all vertices are included in the tree, ensuring the total edge weight is minimized.
https://drawtocode.vercel.app/problems/prims-algorithm
Loading component...
Loading component...
INPUT graph = INPUT: graph = {{ 0, 2, 3, 0, 0}, { 2, 0, 1, 4, 0}, { 3, 1, 0, 5, 6},{ 0, 4, 5, 0, 7}, { 0, 0, 6, 7, 0} };
OUTPUT: A - B ( 2 ) B - C ( 1) B - D ( 4) C - E ( 6 )
public static void main (String[] args) {
V = 3;
graph = new int[][] {{0,1,5},{1,2,3}, {0,2,1}};
primMST();
}//Function End
public static void primMST() {
int[] parent = new int[V];
int[] key = new int[V];
boolean[] mstSet = new boolean[V];
Arrays.fill(key, INF);
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];
}//If End
}//Loop End
}//Loop End
printMST(parent);
}//function end
static final int INF = 99999;
static int V; // Number of vertices
static int[][] graph; // Adjacency matrix
private static int minKey(int[] key, boolean[] mstSet) {
int min = INF, minIndex = -1;
for (int v = 0; v < V; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
}//If End
}//Loop End
return minIndex;
}//function end
static void printMST(int[] parent){
System.out.println("Edge Weight");
for (int i = 1; i < V; i++) {
System.out.println(parent[i] + " - " + i + " " + graph[i][parent[i]]);
}//Loop End
System.out.println();
} // Function End