-
Notifications
You must be signed in to change notification settings - Fork 1
/
Prim.java
49 lines (36 loc) · 1.08 KB
/
Prim.java
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
import java.util.ArrayList;
import java.util.PriorityQueue;
public class Prim {
ArrayList<ArrayList<Pair>> graph;
public int prim() {
PriorityQueue<Pair> pq = new PriorityQueue<>();
boolean[] visited = new boolean[graph.size()];
int weight = 0;
pq.add(new Pair(0, 0));
while (!pq.isEmpty()) {
Pair current = pq.poll();
if (visited[current.index])
continue;
visited[current.index] = true;
weight += current.value;
for (Pair edge : graph.get(current.index)) {
if (visited[edge.index])
continue;
pq.add(edge);
}
}
return weight;
}
static class Pair implements Comparable<Pair> {
public int index;
public int value;
public Pair(int index, int value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Pair other) {
return Integer.compare(this.value, other.value);
}
}
}