0% found this document useful (0 votes)
14 views

Mstttsamgsjs

Uploaded by

ALWIN YABESH A
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)
14 views

Mstttsamgsjs

Uploaded by

ALWIN YABESH A
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/ 2

From a given vertex in a weighted connected graph, implement a program to find the

minimum spanning tree (using priority queue):

SOURCE CODE:

import java.util.*;

class Main {
static class Edge {
int dest, weight;
public Edge(int dest, int weight) {
this.dest = dest;
this.weight = weight;
}
}
static int primMST(List<List<Edge>> graph, int startVertex) {
int V = graph.size();
boolean[] inMST = new boolean[V];
int totalWeight = 0;
PriorityQueue<Edge> pq = new PriorityQueue<>(Comparator.comparingInt(e -> e.weight));
pq.offer(new Edge(startVertex, 0));
while (!pq.isEmpty()) {
Edge edge = pq.poll();
int u = edge.dest;
if (inMST[u]) continue;
inMST[u] = true;
totalWeight += edge.weight;
System.out.print("Added vertex to MST: " + u + " ");
System.out.println("Total weight of MST so far: " + totalWeight);
for (Edge e : graph.get(u)) {
if (!inMST[e.dest]) {
pq.offer(new Edge(e.dest, e.weight));
System.out.print("Considering edge: (" + u + " - " + e.dest + ") Weight: " + e.weight + "
");
}
}
}
return totalWeight;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of vertices: ");
int V = scanner.nextInt();
List<List<Edge>> graph = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
graph.add(new ArrayList<>());
}
System.out.print("Enter the number of edges: ");
int E = scanner.nextInt();
System.out.println("Enter edge details (source destination weight):");
for (int i = 0; i < E; i++) {
int src = scanner.nextInt();
int dest = scanner.nextInt();
int weight = scanner.nextInt();
addEdge(graph, src, dest, weight);
}
System.out.print("Enter the starting vertex for MST: ");
int startVertex = scanner.nextInt();
int totalWeight = primMST(graph, startVertex);
System.out.println("Total weight of the minimum spanning tree: " + totalWeight);
scanner.close();
}
static void addEdge(List<List<Edge>> graph, int src, int dest, int weight) {
graph.get(src).add(new Edge(dest, weight));
graph.get(dest).add(new Edge(src, weight));
}
}

OUTPUT:

You might also like