forked from golumall/Graph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrims Algorithm for Mst.java
More file actions
88 lines (88 loc) · 1.56 KB
/
Prims Algorithm for Mst.java
File metadata and controls
88 lines (88 loc) · 1.56 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.Scanner;
class Prims_Algorithm
{
int v;
int g[][];
Prims_Algorithm(int v)
{
this.v=v;
g=new int[v][v];
for(int i=0;i<v;i++)
{
for(int j=0;j<v;j++)
{
g[i][j]=0;
}
}
}
void addEdge(int src,int dest,int weight)
{
g[src][dest]=weight;
g[dest][src]=weight;
}
int minValue(int key[],boolean mstSet[])
{
int min=Integer.MAX_VALUE,minIndex=0;
for(int i=0;i<v;i++)
{
if(key[i]<min&&mstSet[i]==false)
{
min=key[i];
minIndex=i;
}
}
return minIndex;
}
void printMst(int parent[])
{
int tot=0;
for(int i=0;i<v;i++)
{
tot+=g[i][parent[i]];
System.out.println(i+"->"+parent[i]+" "+g[i][parent[i]]);
}
System.out.println("Total Weight "+tot);
}
void primMst()
{
int key[]=new int[v];
int parent[]=new int[v];
boolean mstSet[]=new boolean[v];
for(int i=0;i<v;i++)
{
mstSet[i]=false;
key[i]=Integer.MAX_VALUE;
//parent[i]=0;
}
key[0]=0;
parent[0]=0;
for(int i=0;i<v;i++)
{
int u=minValue(key,mstSet);
mstSet[u]=true;
for(int j=0;j<v;j++)
{
if(g[u][j]!=0&&g[u][j]<key[j]&&mstSet[j]==false)
{
parent[j]=u;
key[j]=g[u][j];
}
}
}
printMst(parent);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int v=sc.nextInt();
int e=sc.nextInt();
Prims_Algorithm graph=new Prims_Algorithm(v);
for(int i=1;i<=e;i++)
{
int src=sc.nextInt();
int dest=sc.nextInt();
int weight=sc.nextInt();
graph.addEdge(src,dest,weight);
}
graph.primMst();
}
}