Skip to content

Commit 22888e9

Browse files
committed
Prims Algorithm for MST
1 parent d385842 commit 22888e9

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Graph_Algorithms/Prims/Prims.java

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
//Prim’s algorithm is also a Greedy algorithm.
2+
//The idea behind Prim’s algorithm is simple, a spanning tree means all vertices must be connected. So the two disjoint subsets of vertices must be connected to make a Spanning Tree and they must be connected with the minimum weight edge to make it a Minimum Spanning Tree.
3+
//Prim's algorithm starts with the single node and explore all the adjacent nodes with all the connecting edges at every step. The edges with the minimal weights causing no cycles in the graph got selected.
4+
import java.util.*;
5+
import java.io.*;
6+
public class Prims {
7+
8+
public static class Pair implements Comparable<Pair>{
9+
int v;
10+
int wt;
11+
Pair(int v, int wt){
12+
this.v=v;
13+
this.wt=wt;
14+
}
15+
public int compareTo(Pair o){
16+
return this.wt-o.wt;
17+
}
18+
}
19+
public static void main (String[] args) throws java.lang.Exception
20+
{
21+
Scanner scn = new Scanner(System.in);
22+
int n = scn.nextInt();
23+
int m = scn.nextInt();
24+
ArrayList<ArrayList<Pair>>graph = new ArrayList<>();
25+
for(int i=0;i<=n;i++){
26+
graph.add(new ArrayList<>());
27+
}
28+
for(int i=0;i<m;i++){
29+
int u = scn.nextInt();//vertex 1
30+
int v = scn.nextInt();//vertex 2
31+
int w = scn.nextInt();//weight between both of them
32+
graph.get(u).add(new Pair(v,w));
33+
graph.get(v).add(new Pair(u,w));
34+
}
35+
long ans = 0;
36+
PriorityQueue<Pair>pq = new PriorityQueue<>();
37+
boolean [] vis = new boolean[n+1];
38+
pq.add(new Pair(1,0));
39+
while(pq.size()>0){
40+
Pair rem = pq.remove();
41+
if(vis[rem.v]==true){//if a vertex is already selected and marked with a lower weight then do nothing and simply move forward
42+
continue;
43+
}
44+
//while removing we mark visited and weight is added due to that vertex i.e minimum
45+
vis[rem.v]=true;
46+
ans+=rem.wt;//adding minimum weights without creating cycle
47+
ArrayList<Pair>nbrs = graph.get(rem.v);
48+
for(Pair nbr:nbrs){
49+
if(vis[nbr.v]==false){
50+
pq.add(nbr);
51+
}
52+
}
53+
}
54+
System.out.println(ans);
55+
}
56+
}
57+
58+
//Time Complexity of Prims Algorithm - O(V+E)

0 commit comments

Comments
 (0)