forked from DhanushNehru/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimsAlgorithm.java
More file actions
54 lines (47 loc) · 1.12 KB
/
PrimsAlgorithm.java
File metadata and controls
54 lines (47 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.lang.*;
import java.util.*;
public class PrimsAlgorithm{
final int V = 4;
int minKey(int[] key,Boolean[] mstSet){
int min = Integer.MAX_VALUE, min_index=-1;
for(int i=0;i<V;i++){
if(key[i]<min && mstSet[i]==false){
min_index=i;
min=key[i];
}
}
return min_index;
}
void printMst(int[] parent,int[][] graph){
for(int i=1;i<V;i++){
System.out.println(parent[i]+" - "+i+"\t"+graph[i][parent[i]]);
}
}
void printMst(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){
PrimsAlgorithm p = new PrimsAlgorithm();
int[][] graph = new int[][]{{0,2,0,3},{2,0,1,4},{0,1,0,5},{3,4,5,0}};
p.printMst(graph);
}
}