Files
daa-lab/primMST.java
T
2026-05-18 20:03:32 +05:30

59 lines
1.5 KiB
Java

import java.util.*;
public class primMST{
static int N;
static int[][] graph;
static void primMST(){
int[] key = new int[N];
boolean[] mstSet = new boolean[N];
int[] parent = new int[N];
Arrays.fill(key, Integer.MAX_VALUE);
key[0] = 0;
parent[0]=-1;
for(int count =0;count<N-1;count++){
int u =-1;
int min = Integer.MAX_VALUE;
for(int i =0;i<N;i++){
if(!mstSet[i] && key[i]<min){
min = key[i];
u = i;
}
}
mstSet[u] = true;
for(int v = 0;v<N;v++){
if(!mstSet[v] && graph[u][v]!=0 && graph[u][v]<key[v]){
key[v] = graph[u][v];
parent[v] = u;
}
}
}
int totalCost = 0;
System.out.println("\nEdges in MST:");
for(int i =1;i<N;i++){
System.out.println(parent[i]+" - "+i+" : "+graph[i][parent[i]]);
totalCost+=graph[i][parent[i]];
}
System.out.println("Total minimum cost: "+totalCost);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("ENter number of vertices:");
N = sc.nextInt();
graph= new int[N][N];
System.out.println("ENter adjacency matrix(0 if no edges): ");
for(int i =0;i<N;i++){
for(int j=0;j<N;j++){
graph[i][j] = sc.nextInt();
}
}
primMST();
sc.close();
}
}