-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimAlgorithm.java
More file actions
53 lines (42 loc) · 1.46 KB
/
PrimAlgorithm.java
File metadata and controls
53 lines (42 loc) · 1.46 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
package graph;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* A <b>Minimum Spanning</b> tree is a subset of the edges of a connected,
* edge-weighted undirected graph that connects all the vertices together,
* without any cycles and with minimum possible total edge weight.
*/
public class PrimAlgorithm {
// Time Complexity - O(E * log(E))
public static void prims(ArrayList<ArrayList<Pair>> adj, int V) {
PriorityQueue<Pair> pq = new PriorityQueue<>(Comparator.comparingInt(p -> p.weight));
boolean[] isVisited = new boolean[V];
int mstCost = 0;
pq.add(new Pair(0, 0));
while (!pq.isEmpty()) {
Pair p = pq.poll();
int curr = p.vertex;
if (!isVisited[curr]) {
isVisited[curr] = true;
mstCost += p.weight;
for (int i = 0; i < adj.get(curr).size(); i++) {
Pair n = adj.get(curr).get(i);
// IMP: We are adding all the costs of edge.
if (!isVisited[n.vertex]) {
pq.add(new Pair(n.vertex, n.weight));
}
}
}
}
System.out.println("Minimum cost:" + mstCost);
}
public static class Pair {
int vertex;
int weight;
public Pair(int node, int cost) {
this.vertex = node;
this.weight = cost;
}
}
}