0% found this document useful (0 votes)
19 views2 pages

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)
19 views2 pages

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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy