0% found this document useful (0 votes)
13 views3 pages

Progb 7

The document contains a Java implementation of Prim's algorithm to generate a Minimum Cost Spanning Tree (MST) for a graph with 5 vertices. It defines methods to find the minimum key, print the MST, and execute the algorithm on a predefined graph. The output lists the edges and their corresponding weights in the MST.

Uploaded by

Mr Naik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views3 pages

Progb 7

The document contains a Java implementation of Prim's algorithm to generate a Minimum Cost Spanning Tree (MST) for a graph with 5 vertices. It defines methods to find the minimum key, print the MST, and execute the algorithm on a predefined graph. The output lists the edges and their corresponding weights in the MST.

Uploaded by

Mr Naik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

7.

Prim’s algorithm to generate minimum cost spanning Tree (MST)

import java.io.*;

import java.lang.*;

import java.util.*;

class MST

private static final int V = 5;

int minkey(int key[], Boolean mstSet[])

int min = Integer.MAX_VALUE, min_index = - 1;

for (int v = 0; v < V; v++)

if (mstSet[v] == false && key [v] < min)

min = key[v];

min_index= v;

return min_index;

void printMST(int parent[], int graph[][])

System.out.println("Edge \tWeight");

for (int i = 1; i < V; i++)

System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);

}
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] == false && graph[u][v] < key [v])

parent[v] = u;

key[v] = graph[u][v];

printMST (parent, graph);

}
public static void main(String[] args)

MST t = new MST();

int graph[][] = new int[][]

{ 0, 2, 8, 6, 8},

{2, 0, 3, 8, 5},

{0, 3, 0, 0, 7},

{ 6, 8, 0, 0, 9},

{ 0, 5, 7, 9, 0}

};

t.primMST(graph);

OUTPUT:

Edge Weight

0-1 2

1-2 3

0-3 6

1-4 5

You might also like